简体   繁体   中英

Call Stack Priority in JavaScript

If 'A' goes into callback queue and 'B' and 'C' both still have to be executed, will A run after B (assuming that its timeout is complete), or will C run first?

I assume it will be A?

When async operation ends the callback goes to the queue and wait there until call stack is empty. After that, the first callback from the queue is moving to call stack. So if there are B and C in the call stack and A is callback function waiting in the queue, A will be run after B and C.

Here is a proof of concept.

 setTimeout(()=> console.log('C'), 500); setTimeout(()=> console.log('B'), 500); for (let i=0; i <= 99999; i++) for (let j=0; j <= 99999; j++) if (i === 9999 && j === 9999) //< Note that the loop still continues after this setTimeout(()=> console.log('A'), 0); //Note the zero

Here is a guide:

https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM