JavaScript Infinitely Looping Slideshow with Delays

JavaScript Infinitely Looping slideshow with delays?

The correct approach is to use a single timer. Using setInterval, you can achieve what you want as follows:

window.onload = function start() {
slide();
}
function slide() {
var num = 0, style = document.getElementById('container').style;
window.setInterval(function () {
// increase by num 1, reset to 0 at 4
num = (num + 1) % 4;

// -600 * 1 = -600, -600 * 2 = -1200, etc
style.marginLeft = (-600 * num) + "px";
}, 3000); // repeat forever, polling every 3 seconds
}

Javascript infinite loop

Just use one setInterval function...

var index = -1;

setInterval(function() {
index = (index + 1) % buttons.length;
buttons[index].focus();
}, 1000);

Infinite Loop in Javascript?

Use setInterval instead of setTimeout:

var carorange = $('.org-car');
setInterval(function () {
carorange.toggleClass('flipimg');
}, 5000);

setInterval has a nother big advantage: You can stop the interval. So if you assign the interval to a variable, like var myTimer = setInterval..., you can stop it at any time using clearInterval(myTimer); :)

JavaScript: I need a continuous loop that won't kill the browser or block the page

You could use the setInterval method which repeatedly calls a function. And then call clearInterval to stop it.

let inner = document.getElementById('inner');let pages = ['mediumspringgreen', 'coral', 'cyan', 'moccasin'];let mouseIsOver = false;let interval = start();let i = 0;
function start() { return setInterval(() => inner.style.background = pages[i++ % 4], 3000);}
inner.addEventListener('mouseenter', () => { mouseIsOver = true; clearInterval(interval); console.log('pause');});
inner.addEventListener('mouseleave', () => { mouseIsOver = false; console.log('continue'); interval = start();});
#inner { width: 100px; height: 100px; background: cyan }.as-console-wrapper { max-height: 1.5em !important; }
<div id=inner></div>


Related Topics



Leave a reply



Submit