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

230
Visualizações
The execution order of setTimeout and AJAX onload callback function

I am fairly new to javascript and after having a basic understanding of how event loop, callback queue and webAPIs work together to achieve asynchronous in Javascript. I have a following simple code including setTimeout and AJAX to test if my understanding of the executing order of code is correct or not.

setTimeout(() => {
  alert('timeout1')
}, 0);
req = new XMLHttpRequest();
req.open("get", "https://reqres.in/api/products/3");
req.onload = function(data) {
  alert('request done'+data.target.responseText);
};
req.send();
alert('123');
alert('456');
alert('789');
hello,world

I was expecting the result to be like:

alert('123') -> alert('456') -> alert('789') -> alert('timeout1') -> alert('request done')

What I was thinking is that first the setTimeout() belongs to browser API ,so it will be popped out from the call stack of javascript and be executed outside of javascript engine, then the scripts keeps on executing the next line of code. As it got to the line req.send(), it will also be executed outside of javascript engine and then the scripts goes on.

And since I set the timeout to be 0 sec, the setTimeout() callback function ()=>{alert('timeout1')} shall be push into the callback queue first before the req.onload callback function function(){alert('request done');} (after all, the request needs to take some time to wait for response, even if it's super quick). So the order of execution after the call stack is empty would be

  1. alert('timeout1')
  2. alert('request done')

But the result is :

alert('123') -> alert('456') -> alert('789') -> alert('request done') -> alert('timeout1')

Apparently my thought is wrong.But I just can't figure it out.

Please correct me if I was wrong on this. Thank you for checking my question!

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