2012-01-26 40 views
0

我很簡單的循環雖然不起作用,但似乎問題來自setTimeout。 我嘗試用倒計時編碼一個小遊戲。jquery setTimeout loop while

while (there is time) { 
    // actions possible to do 

    //my timer function 
} 

所以,如果c是時間

var c = 30; 

while (c > 0) 
{ 
c -= 1;  
setTimeout($("#timer").html(c) , 1000); 
}; 

它不只是一個倒計時,但用戶必須能夠在倒計時過程中做出的行動。 感謝您的幫助!

+1

'c'在每次迭代時被覆蓋,'$(「#timer」)。html(c)'立即被調用。函數包裝器在哪裏? –

+1

編寫這樣的代碼的目的還沒有被提及。問題本身是非常不清楚的。 – Tamil

回答

0

我不明白你在與循環和c變量做,但你濫用setTimeout功能

setTimeout(1000, function(){$("#timer").html(c)}; 

還是不推薦的方法:

setTimeout('$("#timer").html(c)', '1000'; 

docs

5

setTimeout需要一個函數作爲它的第一個參數。此功能將在時間結束時被調用。但是,你在你的示例代碼提供的是

使用setTimeout正確的方法應該是調用$("#timer").html(c)的結果:

setTimeout(function() { 
    // blah blah 
}, 1000); 

我猜你特林像做一個倒計時,並且這裏有一個例子代碼:

function countdown(count, container) {  // declare the countdown function. 
    var $container = $(container); 
    (function step() { 
    $container.html(count);    // set the timer html 
    if (count-- > 0) {      // decrement counter and stop when counter reaches 0 
     setTimeout(step, 1000);    // if counter is not 0, then issue the next timeout 
    } 
    })();          // call step immediately 
} 
countdown(10, '#timer'); 

現場演示是在http://jsfiddle.net/cazSn/2/

PS:使用如果你真的想要實現倒計時,10會更容易。

+0

前綴'c = 10;'通過'var',*或*移動到函數參數:'(function countdown(c){...})(10);'。 –

+0

@RobW感謝您指出。更新我的代碼。 – qiao

+0

現在你已經改變了代碼,我也建議緩存jQuery選擇器。 –

2

setInterval會更好。

var c = 100; 
var intervalID = setInterval(function(){ 
    if (c>0){ 
     $("#timer").html(c); 
     c--; 
    } else { 
     clearInterval(intervalID); 
    } 
}, 1000);