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

172
Views
Javascript timer/counter crashing browser

This code is meant to start a timer when you type something into the text input, that will count every second until it reaches 5 seconds, and then stop. But it keeps spitting out 0 which is creating an endless while loop that crashes the browser. I'm sure I'm missing something obvious here :-/ !?

var secondsPassed = 0;

function setTimer() {
  
  while (secondsPassed <= 5) {
    console.log(secondsPassed);
    setInterval(function() { secondsPassed += 1; }, 1000);
  }
}
<input type="text" onkeyup="setTimer()">

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

It's the wrong way to both set the interval and count time.

I recommend something on the lines of:

var secondsPassed = 0, timerOn = false;
function setTimer(){
   if(timerOn) return;
   var t0 = Date.now();
   timerOn = true;
   var intervalId = setInterval(
       function(){ 
          secondsPassed = Math.round((Date.now()-t0)/1000);
          console.log(secondsPassed)
          if(secondsPassed >= 10){
              clearInterval(intervalId);
              timerOn = false;
          }
       }, 1000
   );
}
<input type="text" onkeyup="setTimer()">

I stopped the timer after 10 seconds, for the case someone wants to test it, but of course, you'll have to stop it otherwise.

about 4 years ago · Juan Pablo Isaza Report

0

Your while loop will never stop because its condition (secondsPassed <= 5) will never evaluate to true, since setInterval isn't synchronous.

You should instead move the condition inside the setInterval.

var secondsPassed = 0;

function setTimer() {
  var interval = setInterval(function() {
    if (++secondsPassed == 5) clearInterval(interval);
    console.log(secondsPassed)
  }, 1000);
}
<input type="text" onkeyup="setTimer()">

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!