2013-01-16 156 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); 
      } 

    });