Variations in the timing of image transitions

Currently, as a GCSE computing student, I am working on being able to modify the interval between different images in my code. Here's what I have so far...

<!DOCTYPE html>
<html>
<body>
<h1> Adjusting Traffic Light Changes </h1>

<img src="RED.jpg" id= "traffic" width="155" height="198">
<script>

var myImage = document.getElementById("traffic");

 var imageArray = ["RED.jpg", "RED-ORANGE.jpg", "GREEN.jpg", "ORANGE.jpg"];

 var imageIndex = 0; 

 function changeImage() 
{
  myImage.setAttribute("src",imageArray[imageIndex]);
  imageIndex++;
  if (imageIndex >= imageArray.length) {
    imageIndex = 0;
 }

}

setInterval(changeImage,1000);

</script>
</body>
</html>+

If you could incorporate parts of this code while adjusting the intervals, it would be perfect.

Answer №1

If you're looking to tackle this problem with JavaScript exclusively:

Check out the official documentation here

// Initialize a timeoutID variable using window.setTimeout(code, [delay]);
var imageTimers = [500, 1000, 2000, 4000];
var timeToChange = Math.random() * 3000; // You can adjust this value as needed
var timer = setTimeout(changeImage, timeToChange);

// Within the changeImage function, update the timeToChange variable.
function changeImage() {
   // Your code logic goes here...
   clearTimeout(timer);
   timeToChange = imageTimers[imageIndex];
   timer = setTimeout(changeImage, timeToChange);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

IE11 is encountering an error with an "Expected identifier" message in the vendor.js file related to Webpack's variable

I encountered an issue with an Expected identifier ERROR code: SCRIPT1010 that is pointing to vendor.js in the WEBPACK VAR INJECTION section. The debugger is highlighting the line with: const { keccak256, keccak256s } = __webpack_require__(/*! ./hash */ ...

How can I address the issue of having multiple console logs within the

I am facing an issue where my code is logging to the console 3 times upon page load and incrementing its index. I cannot figure out why this is happening despite attempting to make adjustments within a useEffect. My project involves using the typewriter-ef ...

Utilize $.get AJAX to extract data from a multidimensional JSON array

Struggling to make two functions work on my form that uses AJAX and jQuery to look up an array. One function is functional while the other seems to be causing confusion with over-analysis and extensive troubleshooting. Any insights into what may be missing ...

Fresh ajax requests are not clearing the current data displayed in the JSP table

My ajax function retrieves data from a servlet and displays it in the page successfully. However, each time a new ajax call is made, the form appends the new data to the existing results instead of replacing them. I need to reset the current values stored ...

How can I focus on a single dimension of a 2D array in C++?

I've been working on creating a battleship game in the console, and I'm currently tackling the task of designing a function that will draw a grid based on a 2-dimensional array. My approach involves: --> Drawing one row with a character repea ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

Extract the data from a dynamically loaded AJAX page

What is the best way to retrieve the values from the form located in add.php? Add.php is a basic file that contains a single form. The submission process is handled by the code snippet below: var $addGroup = $('<div></div>') .load(&a ...

What is the best way to disregard all pathNames and display my index.php file directly from the root of my website?

After a user clicks on a navigation link on my website, the page is loaded into a content window within the same page using JavaScript. I then utilize HTML 5 to modify the URL and create a history entry, resulting in a URL resembling the one mentioned (). ...

Creating Smooth Transitions Between Two Textures Using Three.js, Implementing Zoom and Blend Effects

I have been exploring ways to create a seamless transition between two panoramic cube images in order to achieve a walk-through effect within a room. Utilizing this example as a starting point, I have set up the Scene, Camera, and Mesh SkyBox. My current f ...

Using the useState() hook with a component as an argument

I have a unique idea for my app - I want the App component's state to store another component that it will render. This way, any component should be able to update the state and trigger a re-render of the App component. function HomePage() { retur ...

What benefits does utilizing Microsoft Workflow Foundations offer?

I am currently working with an investor who is pushing for us to utilize Microsoft Work Flow Foundations for our workflow and database. However, I have already created an interactive graph-database using Javascript, Node.Js, and ArangoDB that perfectly su ...

Combining column values with AngularJS

What is the best way to merge column values in AngularJS? ...

Create an array using the keyword "where"

Is it possible in Python to declare an array with the following syntax? arr = [x for x in vec if x < 2] - (Edit: apology for the 'from'. my common error (the eclipse always corrects me)) (or any other statement without an actual loop) ...

Develop a Rails object using AJAX and JavaScript

Within a music application built on Rails, I am attempting to monitor plays for tracks by artists. This involves creating a unique play object each time a visitor plays a track on the site. These play objects are assigned their own distinct IDs and are ass ...

Sending a function in React.js from one functional component to another

I'm facing an issue with my code where I have a function called postaviRutu in the App component that I need to pass to the child component Sidebar. When clicking on an element in Sidebar, I want it to call the postaviRutu function in App. I've a ...

Clear the date range filter for a specific DataTable

After implementing version 1.13.1 of the DataTable, I successfully added a filter by date range along with two buttons - one for applying the filter and the other for resetting it. If you're interested in learning more about Date Range Filter DataTab ...

Condensing text saved in session storage

Is there a way to compress a large string stored in session storage before sending it to a server? The string can be quite sizable, sometimes reaching upwards of 2mb. Are there any compression algorithms that can help reduce the size? ...

Generate a three-dimensional array with irregular edges in Java

I am looking to create a unique ragged 3d array in Java with the following characteristics. Definition: A 2D array is designated by rows and columns. A 3D array comprises slabs, each of which contains a 2D array. The first slab has three rows, the second ...

Tips on how to showcase particular keys from json information in React

Here is a sample of Json data that I have: [ { "serial_number": "test1", "added_at": "2021-02-05T18:58:43.382943Z", "ser_mod": [ { "added_at": "2021-02-06T02: ...

Is it possible to use AJAX in JavaScript to dynamically update page titles?

When loading a new page using AJAX, I am having trouble updating the title. The expected titles should be "Home", "About", and "FAQ". I attempted to solve this by changing the title with the code snippet below, but it only resulted in displaying "undefine ...