jeudi 30 juillet 2020

Why does setTimeout put callback into message queue when the timeout is set to 0?

I know the fact that on invoking setTimeout, the callback will be immediately put into the message queue waiting to be executed. I wonder why they designed it like this in the first place?

Is it not possible to put the callback function into the call stack directly when the browser figures the timeout is set to 0? Or is it because there are some certain important scenarios where you want your callback to wait in the message queue but you don't want any timeout in the meantime?

If this is the case, could someone point out what these certain situations are? I'm a noob in web dev so I'm confused about this design... Thank you!

Edit: Also, what baffles me even more, is that, say there is one callback function, which is going to take like 10 seconds to complete, and it gets put into the message queue and wait there, now the js engine starts to take care of other stuff, when everything in this program is done, the callback is executed now, but my problem is it still will take 10 seconds to complete, so why not just put this function to the end of the program?




Aucun commentaire:

Enregistrer un commentaire