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

321
Visualizações
Why are setTimeout and setInterval working differently in the browser and in Node.js?

let cnt=0;

let i = setInterval(() => {
  console.log(cnt++);
},200)

setTimeout(() => {
  clearInterval(i);
},2000);

When executed in browser this code logs:- 0 1 2 3 4 5 6 7 8 9

But when executed using Node it logs:- 0 1 2 3 4 5 6 7 8

What is the reason for this?

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

0

This is because Chrome does self-correct the drift in setInterval. node (and other browsers) don't. Note that currently specs agree with node, even if there is an active discussion to follow Chrome's behavior.

So in Chrome, it's like if you had a precise

at beginTime + 200
  do fn
at beginTime + 400
  do fn
at beginTime + 600
  do fn
...etc

while in others it will be

at beginTime + 200
  do fn
  at now + 200
    do fn
    ...etc.

But we know there will always be some delay preventing the timer to fire exactly when scheduled, and so in environments without drift correction, we end up with a now that is later the expected time.

So in Chrome, the setInterval job will be in the queue before the setTimeout one, while in other environments, it will come after, because of the drift, even if infinitesimally small.

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