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
React.Js: Onchange Event for Contenteditable
How to Copy JavaScript Object to New Variable Not by Reference
JavaScript .Replace Command Replace Page Text
How to Give Keyboard Focus to a Div and Attach Keyboard Event Handlers to It
How to Disable JavaScript in Chrome Developer Tools
How to Serialize an Object into a List of Url Query Parameters
Can You Do Desktop Development Using JavaScript
Firestore: Query by Item in Array of Document
Chrome Extension: How to Save a File on Disk
JavaScript Regular Expressions and Sub-Matches
How to Stop Babel from Transpiling 'This' to 'Undefined' (And Inserting "Use Strict")
How to Set a Js Object Property Name from a Variable
How to Pass Parameters in Computed Properties in Vue.Js
Jquery - Get Text for Element Without Children Text
What Does the Function Then() Mean in JavaScript