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

314
Visualizações
In javascript, why doesn't the below code exit the loop?
let a = true;
setTimeout(() => {a = false}, 1000)
while(a){console.log(a)}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Because JS is single threaded, setTimeout will run after 1000 ms when the thread is not busy. Since this while loops blocks the thread, the callback of setTimeout has no time to run and thus a stays true forever.

You can find more details on this topic here.

over 4 years ago · Santiago Trujillo Relatório

0

setTimeout is asynchronous function, the provided callback will be executed only when the javascript call stack will be empty. As we have "while(true)" condition, it will always be executing something => call stack will never be empty => setTimeout callback will never be executing. For more info, read about JavaScript Event Loop https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

over 4 years ago · Santiago Trujillo Relatório

0

Let's see this step by step (if this was executed in browsers) :-

let a = true;
setTimeout(() => {a = false}, 1000)
while(a){console.log(a)}
  • let a = true; : You initialized a new variable a to true;

  • setTimeout(() => {a = false}, 1000) : You have told the browser's setTimeout Web API to execute a callback (() => {a = false}) in which we set a to false after minimum of 1 second. Minimum because that callback will not execute unless the JavaScript execution stack (This is where all your JS code is actually executed synchronously) is empty. This callback after 1s gets placed in an event queue and is dequeued from there only when the JavaScript execution stack is empty.

  • while(a){console.log(a)} : This will execute synchronously and block the main thread (where the execution stack is) since a is always true. Our main thread getting blocked means the completion of this operation is too expensive (makes sense since it's infinite logging) and so the JavaScript execution stack couldn't ever be free for any callback available in the event queue. That means () => {a = false} even though available in the event queue will never get a chance to be dequeued and run in our JavaScript execution stack.

The browser's Web API, this JavaScript execution stack and the event queue together forms our event loop for browsers.

JavaScript is single-threaded (remember main thread ?) synchronous language. All the asynchronous behaviour that you see in your web apps or servers is because of the other parts which form the event loop.

Also this is a simplified picture of it. There are more divisions to the event queue but that's beyond the scope of this question.

over 4 years ago · Santiago Trujillo 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