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 mented unable to see the countdown
})
(i),4000);
//alert(1);
}
I am not able to get the count down timer.. whats wrong.. when "alert" is mented unable to see the count down numbers. Please somebody explain how the above code works.. Post some correct code
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 mented unable to see the countdown
})
(i),4000);
//alert(1);
}
I am not able to get the count down timer.. whats wrong.. when "alert" is mented unable to see the count down numbers. Please somebody explain how the above code works.. Post some correct code
Share Improve this question edited Jul 3, 2020 at 15:45 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 30, 2013 at 12:06 NiRUSNiRUS 4,2692 gold badges31 silver badges51 bronze badges 1- ITYM "can please somebody explain why the code above doesn't work"... – Alnitak Commented Apr 30, 2013 at 12:16
2 Answers
Reset to default 5.delay()
only works for jQuery animation methods, not general jQuery methods such as.html()
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/alnitak/t3AA8/
Do not use alert, because alert will stop everything. Use console.log