Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a setTimeout function continuously loop?

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);
like image 504
Kieran Vyas Avatar asked Jun 15 '13 18:06

Kieran Vyas


People also ask

How do you set loop on setTimeout?

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!

Does setTimeout repeat?

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.

Can you make setTimeout synchronous?

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.

How many times does setTimeout () execute the function parameter?

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.


3 Answers

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();
like image 166
george Avatar answered Oct 20 '22 12:10

george


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
});

Demo

like image 21
PSL Avatar answered Oct 20 '22 12:10

PSL


Use setInterval and toggle() instead.

setInterval(function () {
    $(".slide2").toggle();
    $(".slide").toggle();
}, 1000);

jsFiddle example

like image 3
j08691 Avatar answered Oct 20 '22 12:10

j08691