Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 797
NiRUS Avatar asked Jan 17 '26 05:01

NiRUS


1 Answers

  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/

like image 181
Alnitak Avatar answered Jan 19 '26 18:01

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!