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

225
Visualizações
setTimeout inside Promise vs setTimeout

I know that a callback function inside setTimeout() will wait until the timer attached to it expires and the gets pushed into a callback queue. On the other hand, a promise, once fulfilled or rejected gets its callback pushed into a microtask queue, which has higher priority.

My question is which once is faster: a setTimeout inside a promise or a simple setTimeout. If the former one is not placed onto the microtask queue anymore, why is the setTimeout alone running first instead of the other way around?

setTimeout(() => {
  console.log('timeout');
}, 1000);

let promise = new Promise(function(resolve, reject) {
  // This is run automatically, let's run resolve after 1 second
  setTimeout(() => resolve('promise!'), 1000);
});

promise.then(
  (result) => console.log(result),
  (err) => console.log(error)
);

// output: timeout -> promise || and not || promise -> timeout

Now let's suppose I forget the 1 second delay, now the promise will always appear first since the callback scheduled inside the microtask queue has higher priority

setTimeout(() => {
  console.log('timeout');
}, 0);

let promise = new Promise(function(resolve, reject) {
  // This is run automatically, let's run resolve after 1 second
  // setTimeout(() => resolve('promise!'), 1000);
  resolve('');
});

promise.then(() => {
  console.log('promise');
});

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

0

setTimeout is implemented in a way it's meant to execute after a minimum given delay, and once the browser's thread is free to execute it. so, for an example, if you specify a value of 0 for the delay parameter and you think it will execute "immediately", it won't. it will, more accurately, run in the next event cycle (which is part of the event loop - concurrency model which is responsible for executing the code).

Let's take the example for a delay value of 0.

setTimeout(() => {
  console.log('timeout');
}, 0);

let promise = new Promise(function(resolve, reject) {
  setTimeout(() => resolve('promise!'), 0);
});

promise.then(
  (result) => console.log(result),
  (err) => console.log(error)
);

The setTimeout will always log it's result first because it will execute surely in the next event cycle.

The setTimeout in the promise on the other hand, will have 2 event cycles until the console log will execute (one for the promise resolve and the other one for the callback in the setTimeout function).

Please read reason for delays longer then specified - https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified

More about the JS event loop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

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