2012-01-26 41 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);