Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!