Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

355
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda