stopwatch html keyEvent listener to keyup and keydown

30 Views Asked by At

I want to make a stopwatch that starts while spacebar is up, and stops when spacebar is down.

However, it starts right after i have stopped it because the start function is called when the spacebar is up.

Is there any way to prevent this from happening?

window.addEventListener('keyup', (e) => {
  if (e.keyCode === 32) {
    if (elapsedTime == 0) {
      if (status == "started") {
        clearInterval(timerInterval)
        stop();
        status = "stopped";
      } else {
        start();
        status = "started";
      }
    } else {
      reset();
    }
  }
})
1

There are 1 best solutions below

0
ABR On

let counter = 0;
let counterInterval;
let counter_running = false;

function start() {
  counter_running = true;
  counterInterval = setInterval(() => {
    counter++;
    console.log(counter)
  }, 1000);
}

function stop() {
  counter_running = false;
  clearInterval(counterInterval);
}

window.addEventListener('keydown', (e) => {
  if (e.keyCode === 32 && !counter_running) {
    start();
  }
});

window.addEventListener('keyup', (e) => {
  if (e.keyCode === 32) {
    stop();
  }
});

You should change the code to listen for keydown on the spacebar. This way when pressed down, the start function will be called, and on keyup, when the spacebar is released the function stop will be called.

I have added a check if the interval is running, as otherwise it would keep starting intervals and there is only 1 interval needed and the keyup will only stop one.

Something like this simplified version - this should be modified to make the correct changes and include the reset function as you want it to work.