Event loop - event loop

JS event loop

The event loop is also called the message loop, which is the way the browser renders the main thread. In the source code of Chrome, it starts a for loop that does not end. Each loop takes the first task from the message queue for execution, and other threads only need to add the task to the end of the queue at an appropriate time. . In the past, message queues were simply divided into macro queues and micro queues. This statement can no longer satisfy the complex browser environment, and has been replaced by a more flexible and changeable processing method.

According to the official W3C explanation, each task has a different type, and tasks of the same type must be in the same queue, and different tasks can belong to different queues. Different task queues have different priorities. In an event loop, the browser decides which queue to take. But the browser must have a micro-queue, and the tasks of the micro-queue must have the highest priority and must be scheduled and executed first.

rendering main thread

microqueue

delay queue

interactive queue

        other thread

Can the timer in JS achieve accurate timing? Why?

No, because:

1. Computer hardware does not have an atomic clock, so accurate timekeeping cannot be achieved

2. The timing function of the operating system itself has a small amount of deviation. Since the JS timer finally calls the function of the operating system, it also carries these deviations.

3. According to the W3C standard, when the browser implements the timer, if the nesting level exceeds 5 layers, it will have a minimum time of 4 milliseconds, which will cause a deviation when the timing time is less than 4 milliseconds

4. Affected by the event loop, the callback function of the timer can only run when the main thread is idle, so it also brings a deviation

Guess you like

Origin blog.csdn.net/JackieDYH/article/details/130962260