Reputation: 117
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);
Upvotes: 7
Views: 11460
Reputation: 605
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();
Upvotes: 11
Reputation: 207861
Use setInterval
and toggle()
instead.
setInterval(function () {
$(".slide2").toggle();
$(".slide").toggle();
}, 1000);
Upvotes: 3
Reputation: 123739
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
});
Upvotes: 3