something wrong with my this code, the images are supposed to loop infinitely every 1 second after i click the start button. but when i clicked, it showed only the first image then stuck.
<!DOCTYPE html>
<html>
<head>
<h1> The traffic script</h1>
<p> <button type="button" onClick="Cool()"><h2>Start</h2></button> </p>
<script>
function Cool() {
setInterval(function() {
Timer()
}, 1000);
//This will call the Timer function - units are milliseconds
function Timer() // Complete the Timer() function by adding conditional statements to display the images
{
var list = [
"https://i.ibb.co/Km3c7Lb/capture0002.jpg",
"https://i.ibb.co/DL4N0K6/capture0002.jpg",
"https://i.ibb.co/VqnpV4G/capture0001.jpg"
];
var index = 0;
index = index + 1;
if (index == list.length) index = 1;
var image = document.getElementById('red');
image.src = list[index];
}
}
</script>
</head>
<body>
<img id="red" src="https://i.ibb.co/Km3c7Lb/capture0002.jpg">
</body>
</html>
>Solution :
The problem is you use the same index every time.
var index = 0;
index = index + 1;
if (index == list.length) index = 1;
var image = document.getElementById('red');
image.src=list[index];
It is always 1.
- You need to move the declaration out of the function.
- Increment it AFTER you use it.
- Also, you should reset it to 0, not 1, when it reaches the end.
outside of callback
var index = 0;
in callback
var image = document.getElementById('red');
image.src=list[index];
index = index + 1;
if (index == list.length) index = 0;