2013-01-16 262 views
1

所以我正在做一个倒计时到零的javascript倒计时,然后切换div内的文本,以便用户可以继续。这是我的代码:Js倒计时只倒计时一次

<div id="top"> 
    You will be redirected in 10.. 
</div> 

<script type="text/javascript"> 
    $(document).ready(function(){ 
     var timerId = 0; 

      if(timerId == 0){ 
       timerId = window.setInterval(function() { 
        var timeCounter = 10; 
        var updateTime = parseInt(timeCounter,10) - 1; 
        $("#top").html("You will be redirected in " + updateTime + "..."); 

        if(updateTime <= 0){ 
         clearTimeout(timerId); 
         $("#top").html("Click to continue"); 
        } 
       }, 1000); 
      } 

    }); 
</script> 

它的工作原理,但只能从10倒数到9.为什么这是?

回答

2

Timecounter在间隔内,在每次迭代中将其设置为10。为了使倒计时,你必须移动timecounter可变间隔功能外:

<div id="top"> 
    You will be redirected in 10.. 
</div> 

<script type="text/javascript"> 
    $(document).ready(function(){ 
     var timeCounter = 10, 
      timerId = setInterval(function() { 
       $("#top").html("You will be redirected in " + (timeCounter--) + "..."); 
       if(timeCounter <= 0){ 
        clearTimeout(timerId); 
        $("#top").html("Click to continue"); 
       } 
      }, 1000); 
    }); 
</script> 

FIDDLE

+0

如果你没有在西方玩最快枪,并且提出一个草率的但难以理解的答案,你最终可能会获得更好的成绩。 –

+0

@JanDvorak - 我的回答是正确的,只是声明变量应该移动到不同的范围应该足够了,现在我甚至已经添加了一些代码和小提琴。 – adeneo

+0

这是正确的,但它很难理解(制定,而不是想法) –

1

每次定时器结束运行指定的回调。

而在回调(每次给定函数的新实例)内部,您将timeCounter设置为10。

因此,该值始终保持不变。

1

您需要将时间计数器放在window.setInterval()函数之外。

它可以保持在ready函数内但在setInterval()方法之外。

1

你硬编码你的timeCount变量。我的解决办法:

HTML代码:

<div id="top"> 
    You will be redirected in <span id="timer">10<span>.. 
</div> 

Javascript代码

$(document).ready(function(){ 
     window.setInterval(function() { 
      var timeCounter = $('#timer').html(); 
      var updateTime = parseInt(timeCounter,10) - 1; 
      $("#timer").html(updateTime); 

      if(updateTime <= 0){      
       $("#top").html("Click to continue"); 
      } 
     }, 1000); 


}); 

实施例:http://jsfiddle.net/ccAz6/1/

1

DEMO

var timerId = 0; 

var timeCounter=10; 

$(document).ready(function(){ 

      if(timerId == 0){ 
       timerId = window.setInterval(function() { 

        var updateTime = parseInt(timeCounter) - 1; 
        timeCounter--; 

        $("#top").html("You will be redirected in " + updateTime + "..."); 

        if(updateTime <= 0){ 
         clearTimeout(timerId); 
         $("#top").html("Click to continue"); 
        } 
       }, 1000); 
      } 

    });