I have been working with JS for about a year now and I'm still learning it. My question is at the end.
In the first example:
console.log('Start');
setTimeout(()=> console.log('inside callback'), 0);
console.log('End');
outputs
Start
End
inside callback
I understand that even though the timeout is 0
, it still had to go to browser WebApi (setTimeout api) and immediately pushed into callback queue waiting for the main thread to be free (which is currently executing console.log('End')). Once the thread is free callback is executed & "inside callback" is printed.
Following this approach, I tried to experiment it with another WebAPI i.e DOM API.
This time, Instead of setTimeout, I used document.querySelectorAll()
console.log('Start');
console.log(document.querySelectorAll('img'))
console.log('End');
Outputs
Start
NodeList(4) [img.bar-sm.-avatar.js-avatar-me, img.bar-sm.avatar.s-avatar--image, img, img]
End
This time we see DOM API output before END is printed.
I know the output but I want to understand the flow behind it.
Why it didn't follow the pattern like setTimeout?
Why didn't the DOM output came after "End" if it was processed on separate thread.
Did it follow the flow below:
document.querySelectorAll -> webAPI -> callback queue -> main thread
Does DOM API have to go though callback queue and wait for main thread to be empty. If so? how come we got consoles in the right order this time unlike with setTimeout
I'm still learning and would appreciate explanation a lot. Please point anything if I misunderstood. Thanks.