How can I make a setTimeout function continuously loop?
For example
setTimeout(function(){
$(".slide2").hide();
$(".slide").show();
setTimeout(function(){
$(".slide").hide();
$(".slide2").show();
}, 1000);
}, 1000);
Simply wrap up the setTimeout code inside an IIFE. Set the timeout from within a function outside the for loop then call the function from inside the loop. Feel free to share your tips and experiences too!
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
setTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack. In other words, you cannot use setTimeout() to create a "pause" before the next function in the function stack fires.
The JS setTimeout() method will call a function after the time specified in milliseconds (1000 ms = 1 second) has passed. The specified function will be executed once.
setInterval
is actually evil, if the code inside the setInterval takes longer than the time you have set it will create another process before the function finishes messing everything up. So choosing setTimeout
is actually better.
To make a function loops in setTimeout
use a following syntax:
function function1() {
console.log({} + [] + " = {} + []"); // run this it is actually funny
}
function runner() {
function1();
setTimeout(function() {
runner();
}, time);
}
runner();
You can reduce your nesting, and probably use setTimeout and toggle will take care of the rest (show your first element by default before executing.).
function slideEm()
{
$(".slide2").toggle();
$(".slide").toggle(); // Make this visible first
window.setTimeout(slideEm, 1000);
}
slideEm();
Or use setInterval
function slideEm()
{
$(".slide2").toggle();
$(".slide").toggle(); // Make this visible first
}
$(function(){
$('.slide').show(); //Using css hide both of them and show this first
window.setInterval(slideEm, 1000); // start the callback loop with a sec interval
});
Use setInterval
and toggle()
instead.
setInterval(function () {
$(".slide2").toggle();
$(".slide").toggle();
}, 1000);
jsFiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With