0

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!

mplungjan
  • 169,008
  • 28
  • 173
  • 236
mrWayne
  • 21
  • 3
  • 4
    debugging with alerts is bad since it causes pauses in execution. You really should use console.log() – epascarello Nov 29 '21 at 15:50
  • _“What I was thinking is that first the `setTimeout()` belongs to browser API”_ — Why would that make a difference? Both `setTimeout` and XHR are Web APIs. What makes a difference is which queue in the event loop the functions will be added to. – Sebastian Simon Nov 29 '21 at 15:51
  • @SebastianSimon Yeah I understand that both setTimeout and XHR are web APIs. What I'm confused about is the executing order. I though that the setTimeout call back function is the first entering into the call back queue, and then is the onload call back function . So I assumed "alert('timeout1')" will appear first , then is the alert('request done'). Thanks for your reply! – mrWayne Nov 30 '21 at 10:22

0 Answers0