2012-01-19 87 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);