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

219
Visualizações
js setTimeout() finishes instantly without any rest

when coding, I came upon this very weird problem. My code is below: js

document.getElementById("id").style.width = "0%"
var a = 0;
setTimeout(function () {
    if (a <= 60) {
        document.getElementById("id").style.width = a + "%";
        a++;
    }
}, 100);


I want it to run 60 times, each time changing the div's width by 1% However, when I run the code, the if block makes it finish instantly as if the timeout didn't work. Can anyone tell me what's wrong? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

setTimeout function executes only once after that specified time in milli seconds.

If you want to keep on executing the block, you have to make use of setInterval instead of setTimeout.

setInterval keeps on calling the function since the interval is cleared.

Dont forget to call clearInterval once target achieved.

var a = 0;
const interval = setInterval(function () {
    if (a <= 60) {
        console.log("Im being called");
        document.getElementById("id").style.width = a + "%";
        a++;
    } else {
      // Target achieved, clearing interval
      console.log("Im stoping execution");
      clearInterval(interval)
    }
}, 100);
#id {
  height: 300px;
  background: orange;
}
<div id="id"></div>

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