Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!