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

345
Views
Why isn't my code running before the interval completes?

In the snippet, I want the color of timer to change to red before the alert pops up.

I have written $("#timer").css('color', 'red'); before alert("Time Up!"), so logically it should change the text color before showing the alert, but it is changing color after displaying the alert.

let time = 3;

$(function() {
  let interval = setInterval(function() {
    time--;
    
    if (time >= 0)
      document.getElementById("timer").innerHTML = time + "";
    else {
      $("#timer").css('color', 'red');
      clearInterval(interval);
      alert("Time Up!")
    }
  }, 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="timer">3</h1>

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

0

The issue is because the alert() blocks the UI from updating, and although you call css() before alert(), there's not enough time to update the DOM before the alert appears and temporarily prevents any further rendering.

To fix this, place the alert() call in a timeout with a short delay. This allows the UI to be updated before the alert() is displayed:

let time = 3;

jQuery($ => {
  let interval = setInterval(function() {
    time--;
    
    if (time >= 0) {
      $("#timer").html(time);
    } else {
      $("#timer").css('color', 'red');
      clearInterval(interval);
      setTimeout(() => alert("Time Up!"), 0);
    }
  }, 1000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id="timer">3</h1>

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!