2012-01-19 83 views
1

我想在jQuery中創建一個計時器,我希望每秒更改一次span的值,但是這種延遲不起作用。循環內部的jQuery延遲

function startTimer(daysRemain,hoursRemain,minutesRemain,secondsRemain){ 

      while(secondsRemain < 60){ 
       secondsRemain++; 
       $("span.secondRemain").delay(1000).text(secondsRemain); //change value of seconds each one second 
       // I try this way too! 
       /* setTimeout(function(){ 
        $("span.secondRemain").text(secondsRemain); 
       },1000);*/ 

      } 

回答

3

delay僅用於fx隊列。

一個標準定時器是如下

var t = 0; 
setInterval(function() { 
    $('div').text(t); 
    t += 1; 
},1000); 

http://jsfiddle.net/J9Zwa/

+0

嗯,你是對的,但我試過的setTimeout太也不起作用。 – palAlaa

+0

'setTimeout'只會調用一次。您可以在初始的'setTimeout'中再次調用'setTimeout'或者使用'setInterval''參見我的編輯以獲取基本的定時器示例。 – Trevor

1

.delay()不耽誤您運行的JavaScript。它進入動畫隊列,當隊列到達該操作時,它會爲延遲時間設置一個計時器,並且不會繼續進行到隊列中的下一個操作,直到經過很長時間。

因此,你不能在你的循環中使用它來使JavaScript延遲。您需要像這樣使用setTimeout()

function startTimer(daysRemain,hoursRemain,minutesRemain,secondsRemain) { 

    function nextTime() { 
     if (secondsRemain < 60){ 
      secondsRemain++; 
      $("span.secondRemain").text(secondsRemain); //change value of seconds each one second 
      setTimeout(nextTime, 1000); 
     } 
    } 
    nextTime(); 
} 
1

你試過:

setInterval(function(){ 
    $("span.secondRemain").text(secondsRemain); 
},1000);