Swapnil
Swapnil

Reputation: 47

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>

Upvotes: 2

Views: 28

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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>

Upvotes: 2

Related Questions