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