2012-07-26 105 views
0

我正在进行一个简单的游戏。它几乎完成除了计时器有一个小故障,我不知道什么是做它。当你按下一个按钮时,画布上的HTML5文本开始从35倒数到0.在第一次运行时,它很好。但是如果你选择重新玩刷新计时器开始倒计时更快。这里是代码。第二次运行时计时器的计数更快

var timer = 35; 

ctx.fillText("Countdown: " + timer, 320, 32); 

function resetReggie(){ 
    reggie.x = canvasWidth/2; 
    reggie.y = canvasHeight/2; 
} 

//Starts Timer for Timed Game 
function timedMsg() 
{ 
    resetReggie(); 
    ballsCaught = 0; 
    timer = 35; 
    alert('Pick up as many as you can in ' + timer + ' seconds'); 
    countDown(); 
     var t=setTimeout(function() { 
     var again = confirm("TIMES UP! You Gathered " + ballsCaught + " Balls! Play Again?"); 
      if (again === true){ 
       timedMsg(); 
       resetReggie(); 
      } 
       if (again === false){ 
       resetReggie(); 
       ballsCaught = 0; 
       timer = 35; 
       } 
     }, timer * 1000); 

} 

function countDown() { 
    if (timer != 0){ 
     timer-=1; 
     setTimeout('countDown()', 1000); 
    } 
} 
+0

因为你正在改变'timer'它开始,'countDown'确实每次'计时器 - = 1;',然后将其在你的'setTimeout'中使用,以确定等待的时间。/ – Gavin 2012-07-26 14:20:13

+1

如果你每秒钟倒计时,为什么你还需要另一个计时器35秒? – 2012-07-26 14:24:12

回答

1

我想:

试试这个问题是在线

}, timer * 1000); 

你在哪里有一个值th在最多为34时'计时器'被评估为设置超时。因为你将它初始化为35,但是然后调用countDown()将其减少到34,那么你有一个调用confirm()的方法可以让'timer'减少更多。结果,随后对timedMsg()的调用发生得有点过快,导致countDown()被频繁调用两次。尝试以下的(我跑它在节点),然后改变为4〜6。

function countDown() { 
    console.log("Countdown: " + timer, 320, 32); 
    if (timer != 0) { 
     timer -= 1; 
     setTimeout(countDown, 1000); 
    } 
} 
function timedMsg() { 
    timer = 5; 
    countDown(); 
    var t=setTimeout(function() { 
     timedMsg(); 
    }, 4 * 1000); 
} 
timedMsg(); 
+0

谢谢,我调整了一下,但这种方法最终为我工作。现在完成了!再次感谢你。 – ZombiEquinox 2012-07-26 15:16:17

0

正如我在评论中提到的那样,每次开始新游戏时,看起来您都在减少超时值。结果,这减少了每次的时间。在控制台(在Chrome F12)

var timeout = currentTime = 5; 
var int = setInterval(function() { 
    ​console.log(currentTime); 
    currentTime--; 
    if(currentTime < 0) { 
    var again = confirm('Play again?'); 
    if(again) { 
     currentTime = timeout; 
    } 
    else { 
     clearInterval(int); 
    } 
    } 
}, 1000);​ 

http://jsfiddle.net/gRoberts/CsyYx/

看,或更新的代码写入到浏览器中看到它的工作;)