An automatic image rotator builds on the manual JavaScript image slideshow by scheduling the next slide after a delay. The original tutorial used setTimeout(); the same approach is retained with a function callback instead of a string callback.
timerId = setTimeout(() => showNext(1), 3000);
The original page used:
setTimeout("displaynext(1)", 3000);
String callbacks are legacy style. Pass a function instead:
timerId = setTimeout(() => showNext(1), 3000);
The delay is still in milliseconds. See the related JavaScript timer tutorials.
An automatic rotator usually continues instead of stopping at the final slide. Modulo arithmetic keeps the index inside the array.
current = (current + 1) % images.length;
Store the timeout ID so an existing schedule can be cancelled before creating a new one. This avoids stacking multiple timers when Start is clicked repeatedly.
function schedule() {
clearTimeout(timerId);
timerId = setTimeout(() => {
current = (current + 1) % images.length;
render();
schedule();
}, 3000);
}
The original page showed the modified displaynext() source. The complete working rotator is provided here so users can copy the entire example.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Automatic image rotator</title>
</head>
<body>
<img id="rotator" src="images/help.jpg" alt="Rotator image 1">
<button type="button" id="start">Start</button>
<button type="button" id="stop">Stop</button>
<span id="status" aria-live="polite"></span>
<script>
const images = ['images/help.jpg', 'images/help2.jpg', 'images/correct.jpg', 'images/wrong.jpg'];
const image = document.getElementById('rotator');
const start = document.getElementById('start');
const stop = document.getElementById('stop');
const status = document.getElementById('status');
let current = 0;
let timerId = null;
function preload(index) {
const preloader = new Image();
preloader.src = images[index];
}
function render() {
image.src = images[current];
image.alt = `Rotator image ${current + 1}`;
status.textContent = `${current + 1} / ${images.length}`;
preload((current + 1) % images.length);
}
function schedule() {
clearTimeout(timerId);
timerId = setTimeout(() => {
current = (current + 1) % images.length;
render();
schedule();
}, 3000);
}
start.addEventListener('click', schedule);
stop.addEventListener('click', () => {
clearTimeout(timerId);
timerId = null;
});
render();
schedule();
</script>
</body>
</html>
Image Object Manual image slideshow
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.