Search code examples
javascripttimekeyevent

Javascript start stopwatch after keyevent


I'am working on a game with the canvas element. The goal is that first time you press a key it start a stopwatch. It should end as soon as the gameoverscreen/winscreen appears.

After the gameoverscreen/winscreen it should work like befor(if press key than start stopwatch)

The problem is that that the function only once called can be.

The Code(the most important part):

function startTime(){
    startTime = function(){};
    var count = 0;
    function stopwatch(){
        if(winScreen || gameOver){ 
            count = 0;
        } else{
            console.log(count++);
        }
    }
    setInterval(stopwatch, 1000);
}
document.addEventListener('keydown', function(event){
    startTime();
});

Is there a way to solve that problem?


Solution

  • The cause of your problem is that you are overwriting startTime with an empty function on the second line. The second time you call startTime(), it runs the empty function.

    To keep your code clean, your stopwatch shouldn't really check for the win or game over conditions - it should only keep track of the count. The rest of your game code can start and reset the stopwatch whenever those conditions occur. You could have a stopwatch object like this:

    var stopwatch = {
      count: 0,
      
      intervalId: null,
      
      start: function() {
        stopwatch.intervalId = setInterval(function() {
          stopwatch.count++;
        }, 1000)
      },
      
      reset: function() {
        if (stopwatch.intervalId) {
          clearInterval(stopwatch.intervalId);
          stopwatch.intervalId = null;
        }
        stopwatch.count = 0;
      }
    }

    Then your game can call stopwatch.start() when it starts and stopwatch.reset() when it ends.

    Note that it also clears the interval when it resets. Without this, the function inside setInterval would get duplicated every time, causing potential bugs and a memory leak.