Home  >  Q&A  >  body text

Please look at these four setTimeout functions and their execution parts

//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?

P粉304704653P粉304704653398 days ago554

reply all(1)I'll reply

  • P粉709307865

    P粉7093078652023-09-18 13:33:27

    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:

    第三个setTimeout(0毫秒延迟)
    第二个setTimeout(3000毫秒延迟)
    第一个setTimeout(5000毫秒延迟)
    第四个setTimeout(7000毫秒延迟)

    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:

    1. bye
    2. hello
    3. hi
    4. 从10000打印到0(降序)
    5. 代码执行时间为...毫秒

    reply
    0
  • Cancelreply