Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda