//1 setTimeout(() => { console.log('hi'); }, 5000) //2 setTimeout(() => { console.log('hello'); }, 3000) //3 setTimeout(() => { console.log('bye'); }, 0) //4 setTimeout(() => { console.time('the code took:'); let i = 10000 while (i--) { console.log(i); } console.timeEnd('the code took:') }, 7000)
Here I wrote four setTimeout functions. According to my understanding, they will start executing at the same time in the callback queue, right? If I'm right, then my question is whether the fourth setTimeout() function has completed half or more than half of its execution in the callback queue or does it start from the beginning after 7 seconds after being pushed into the call stack implement? So what's going on behind the scenes?
These functions will not run in parallel or simultaneously in the callback queue. They are scheduled individually and asynchronously. The order of execution depends on the specified latency of each function. For each setTimeout function, a callback is scheduled to execute after the specified delay.
The execution sequence is as follows:
However, The fourth setTimeout function does not necessarily run with other setTimeout functions, nor is its own execution time guaranteed. The execution order is determined by the callback queue, and the event loop gets tasks from the callback queue and runs them in the call stack only when the call stack is empty. Therefore, the fourth setTimeout function will only start executing when there are no other tasks in the call stack. After running the given code, the output should appear in the following order:
The following is the sequence of output: