Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

347
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda