3

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

1
  • ITYM "can please somebody explain why the code above doesn't work"... Commented Apr 30, 2013 at 12:16

2 Answers 2

5
  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/

Sign up to request clarification or add additional context in comments.

6 Comments

yes i do agree with that.. delay is not my concern here.. but in my question above when i have alert it works fine.. when i comment it out it goes crazy.. how is the execution happening..
the alert is most likely just given the system time to process the timeout events. You should use console.log for debugging instead of alert.
ok i used console.log instead of alert.. i am getting all the numbers 6 to 0 in the log. But i am not able to see the same in the div tag using delay and timeout. Kindly check the code yourself on JSfiddle and explain how the things are getting fired.. thank you..
like I told you, .delay() doesn't work on most jQuery methods. You call that code from 6..0 and without the alert nothing stops it from immediately reaching the 0 iteration and overwriting the div with that value. Did you even try my code?
yes i tried it and used it in my program . thank you for that.. as per my knowledge javascript execution doesnt happen sequentially...
|
0

Do not use alert, because alert will stop everything. Use console.log

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.