mrWayne
mrWayne

Reputation: 21

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!

Upvotes: 0

Views: 113

Answers (0)

Related Questions