最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - SetTimeout javascript countdown Timer with delay - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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/alnitak/t3AA8/

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

发布评论

评论列表(0)

  1. 暂无评论