Search code examples
javascriptjquerysettimeoutcountdowntimerjquery-events

SetTimeout javascript countdown Timer with delay


hi i am confused with the below code

JSfiddle link

for (var i=6;i>=0;i--)
    {
       
        setTimeout((function(i)
              {
                  
            $("div").delay(4000).html(i);
            alert(i); //if commented unable to see the countdown
            
              })
            (i),4000);
        //alert(1);
        
    }
        

I am not able to get the count down timer.. whats wrong.. when "alert" is commented unable to see the count down numbers. Please somebody explain how the above code works.. Post some correct code


Solution

    1. .delay() only works for jQuery animation methods, not general jQuery methods such as .html()

    2. All of your timeouts are getting fired at once - there's nothing to space them out.

    The net result is that (without an alert) every iteration through the loop runs immediately, leaving the div containing 0 having invisibly (and very briefly) contained the other numbers from the previous iterations.

    Try this, instead:

    function counter($el, n) {
        (function loop() {
           $el.html(n);
           if (n--) {
               setTimeout(loop, 1000);
           }
        })();
    }
    
    counter($('div'), 6);
    

    See http://jsfiddle.net/alnitak/t3AA8/