简体   繁体   中英

Timer counting faster on second run

I am working on a simple game right now. its almost done except for the timer has a glitch in it and I can't figure out whats doing it. when you push a button, an HTML5 text on the canvas starts to count down from 35 to 0. On the first run it's fine. But if you choose to play again with out refresh the timer starts to countdown faster. here is the code.

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);
    }
}

I think the problem is in the line

    }, timer * 1000);

where you have a value that is at most 34 at the time 'timer' is evaluated to set the timeout. Because you initialize it to 35 but then call countDown() which decreases it to 34, then you have a call to confirm() which might let 'timer' decrease even more. As a result the subsequent call to timedMsg() happens a little too soon causing countDown() to be called twice as often. Try the following (I ran it in node) and then change the 4 to 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();

As mentioned in my comment, each time you start a new game, it appears you are decreasing the timeout value. As a result, this reduces the time each time.

Try this:

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/

Look at your console (F12 in Chrome), or update the code to write to the browser to see it working ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM