Search code examples
jqueryhtmlfor-loopdelay

delaying updating value in a for loop


I want to update my price on my webpage with some eyecandy.
What I currently have:

$(document).ready(function() {
        $("#table1").fadeIn(1000, function myLoop()
        {
        var price = 60;

        for ( var i = 0; i <= price; i++ ) {
                $("#price").html("€" + i);              
            }
        });     
    });

I need a delay in my For loop so you can see the price iterate upwards.
Any help is being appreciated!


Solution

  • In event-oriented environments like web programming, you don't put delays in your code; instead, you yield back to the environment and ask it to call you back in a little while.

    In browsers, you do that using setTimeout (for a one-off) or setInterval (for an ongoing, repeated timer). For what you're doing, I'd use setTimeout and schedule each new iteration as required.

    Here's an example:

    $(document).ready(function() {
        $("#table1").fadeIn(1000, function myLoop()
        {
            var price = 60;
            var i = 0;
    
            loop();
    
            function loop()
            {
                $("#price").html("€" + i);              
                if (i < price) {
                    ++i;
                    setTimeout(loop, 100); // 100ms = 1/10th second
                }
            }
        });     
    });
    

    There, we start with i being 0 and call loop, which updates the price and then, if i is less than price, asks the browser to call it back again in 100ms (a tenth of a second). When that happens, it shows that updated i value, then repeats the process until i is no longer less than price.

    This works because loop is a closure over i and price, which means it has an enduring reference to those variables, even after the fadeIn callback has returned (which it does after the first time loop runs). More about closures (on my blog): Closures are not complicated