Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
I created a stopwatch using JavaScript, and I'm trying to start/stop the timer by space key, but it doesn't stop but always became more faster

I created a stopwatch using JavaScript, and I'm trying to start/stop the timer by space key, but it doesn't stop but always became more faster. '''

var timer_start = "S";

var time;
document.body.onkeyup = function (e) {
  if (e.keyCode == 32) {
    time = setInterval(timer, 10);
    if (timer_start == "S") {
      timer_start = "F";
    } else if (timer_start == "F") {
      clearInterval(time);
      timer_start = "S";
    }
  }
};

,,,

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Once the spacebar is pressed, you are starting the timer again regardless of the current value of timer_start. You need to move this to be inside the if statement. I'd also recommend using a Boolean instead of the string "S" and "F".

Here is my proposed rewrite of your code:

var timer_start = true;

var time;
document.body.onkeyup = function (e) {
  if (e.keyCode == 32) {
    if (timer_start) {
      time = setInterval(timer, 10);
      timer_start = false;
    } else {
      clearInterval(time);
      timer_start = true;
    }
  }
};

You could also shorten it a bit by doing this if you wanted

var timer_start = true;
var time;
document.body.onkeyup = function (e) {
  if (e.keyCode == 32) {
    if (timer_start) {
      time = setInterval(timer, 10);
    } else {
      clearInterval(time);
    }

    timer_start = !timer_start
  }
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

You set the interval regardless of the timer_start state, so you keep piling up new intervals and remove only half of them. You should set the interval only in the timer_start == "S" branch.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda