preface

A problem raised by the student’s work involves the question of whether to queue the setTimeout code immediately when it is encountered and wait until the timer expires to execute the callback or wait until the timer expires and then queue the callback.

The body of the

This issue relates to the concept of macro tasks in JS and message queues in the V8 engine.

As can be seen from the above data, the setTimeout callback function will be put into the message queue only when the timing time is up. However, the specific execution time is not only determined by the timing time, but also depends on the current execution stack and the execution time of the current Event loop. Therefore, the timing time is equivalent to a start time.

As for how to remember the timing time of each setTimeout and put it into the message queue after the timing, as far as I know, the timer scheduling strategy is complicated, and there will be a special scheduling strategy to add the corresponding callback task at an appropriate time. Personally, I also prefer the asynchronous processing module to deal with this. However, in daily development, it is not recommended to speculate about the results of the underlying operation mechanism, because the execution time of setTimeout is a variable. We know its start time, but we cannot know the specific execution time. Therefore, in order to ensure the reliability of code logic, we should not pile up various timing functions. Use asynchronous functions such as Promise or async to ensure that the code is executed in the correct order.

The latter

References:

Microtasks, macro tasks, and Event-loops

See the Big from the small – from setTimeout extension JS several major features

V8 engine details (8) – message queuing

PS: in searches for this topic, spotted a fix (Js asynchronous, event loop with a message queue, micro tasks and macro task), describes the different combination between micro macro task task execution order, after watching the overcame my fear of similar questions before the interview, if a friend in need can go to take a look at the title.

If there is any mistake, welcome to correct ~