Search code examples
javascriptjqueryhtmlloopsdelay

jQuery how to loop a function after a series of delay


I have a function which has a series of several delayed functions:

function greet(t) {
    $("div").delay(t*2).queue(function(n) {
         $(this).html("Bonjour");
        n();
    });

    $("div").delay(t*3).queue(function(n) {
         $(this).html("Hola");
        n();
    });

    $("div").delay(t*4).queue(function(n) {
         $(this).html("Hallo");
        n();
    });

    $("div").delay(t*5).queue(function(n) {
        $(this).html("Hello"); // back to original
        n();
    });
}

greet(500);

With a simple <div>Hello</div> in HTML. This way, the greeting changes language every 500ms.

After the function completes (which takes about 2 seconds; 2000ms) I want to start the function over and have loop it infinitely. So, I tried the usual:

    setTimeout(function() {
       greet(500);
    }, 2500); // after 2500ms, repeat the function

If you notice, once it loops through twice, it stops at "Hello". Why is this? Here is a fiddle displaying my problem http://jsfiddle.net/rgX6B/2/

Any help would be much appreciated!

Edit:

I actually simplified my problem for the sake of asking a question. I didn't want to post a big wall of code (the changing of the inner html are actually complex functions that involve changing the positioning of CSS shapes.) My problem was ultimately solved by putting the setTimeout inside the function. Thank you all for your answers!


Solution

  • You just have to use it in your function

    http://jsfiddle.net/kelunik/rgX6B/4/

    function greet(t) {
        $("div").delay(t*1).queue(function(n) {
             $(this).html("Bonjour");
            n();
        });
    
        $("div").delay(t*2).queue(function(n) {
             $(this).html("Hola");
            n();
        });
    
        $("div").delay(t*3).queue(function(n) {
             $(this).html("Hallo");
            n();
        });
    
        $("div").delay(t*4).queue(function(n) {
            $(this).html("Hello"); // back to original
            n();
        });
    
        setTimeout(function() {
           greet(500);
        }, 500);
    }
    
    greet(500);
    

    another solution would be to use setInterval(function() { greet(..) }, 3000);