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

342
Visualizações
javascript setTimeout() and using for loop after and consume the value of the for loop in the setTimeout()

My question is variant of this question: setTimeout executes after for loop in javascript

The code:

let i = 0;

setTimeout(() => alert(i), 100); // ?

// assume that the time to execute this function is >100ms
for(let j = 0; j < 100000000; j++) {
  i++;
}

The output:

100000000

My Question: I know that when we're using setTimeout with delay of 100 the WEB API setTimeout() will move to the queue of the eventloop and after that will get inside the call stack if it's empty and available. We can see that this setTimeout will start after 100ms so i thought maybe the i value would be somthing like 4000+ or somthing like that. but unfortunately (with this big loop that take like 5+- seconds that is 5000ms) the setTimeout function will be executed just after the for loop finishes! but the event loop daemon is running and ready to accept the setTimeout callback because the call stack is empty. I know that JS concurrency concept is diffrent from languages just like JAVA&C++, etc... that there is no scheduler for the CPU time because it's one threaded language, but I guess that the event loop working like OS daemon and ready to accept the message from the queue even if the CPU is busy with the for loop. so the reason that it's happening is because the CPU is busy and can't execute the eventloop ? or there is other reason? Thanks guys!

about 4 years ago · Juan Pablo Isaza
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