Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How do setTimeout and setInterval understand

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to understand setTimeout and setInterval". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand setTimeout and setInterval.

Javascript thread interpretation (setTimeout,setInterval what you don't know)

JavaScript's setTimeout and setInterval are two easy ways to deceive other people's feelings, because at first we often think that if we call it, it will be carried out in a given way. I think many people feel the same way, such as

SetTimeout (function () {

SetInterval (callbackFunction, 100)

It is considered that the greeting method in setTimeout will be executed immediately, because it is not said out of thin air, but the JavaScript API document clearly defines how many milliseconds the second parameter means, the callback method will be executed. If it is set to 0 milliseconds, it will be executed immediately.

By the same token, I firmly believe that setInterval's callbackFunction method is executed immediately every 100ms!

But with the increasing experience of JavaScript application development, one day you find a strange piece of code and wonder:

Div.onclick = function () {

SetTimeout (function () {document.getElementByIdx_x ('inputField') .focus ();}, 0)

}

Since it is executed in 0 milliseconds, then why use setTimeout? at this moment, firm belief has begun to shake.

Until the last day, you accidentally wrote a bad piece of code:

SetTimeout (function () {while (true) {}}, 100)

SetTimeout (function () {

SetInterval (callbackFunction, 200)

The first line of code enters an endless loop, but you will soon find that the second and third lines are not expected, alert greetings are not seen, and callbacKFunction is not heard from!

At this point, you are completely lost, and this situation is unacceptable, because the process of changing the long-established perception to accept new ideas is painful, but the facts are right in front of you, and the search for JavaScript truth will not stop because of pain. Let's start the exploration of JavaScript threads and timers!

Pull out the clouds and see the moon

One of the main reasons for all the above misunderstandings is that subconsciously there are multiple threads in the JavaScript engine and the timer callback function of JavaScript is executed asynchronously.

In fact, JavaScript uses a blindfold and deceives us most of the time, and here the backlight has to clarify one fact:

The JavaScript engine runs in a single thread, and the browser runs JavaScript programs with only one thread at any time.

It also makes sense for the JavaScript engine to run with a single thread, which is simplified without paying attention to complex problems such as thread synchronization.

So how does the single-threaded JavaScript engine cooperate with the browser kernel to handle these timers and respond to browser events?

The following is a simple explanation combined with the processing method of the browser kernel.

The browser kernel implementation allows multiple threads to execute asynchronously, and these threads cooperate with each other under kernel control to keep synchronized. If the implementation of a browser kernel has at least three resident threads: the javascript engine thread, the interface rendering thread, and the browser event trigger thread, in addition to some threads that terminate after execution, such as the Http request thread, these asynchronous threads will produce different asynchronous events. Here is a diagram to illustrate how the single-threaded JavaScript engine interacts with other threads. Although the implementation details of each browser kernel are different, the principle of calling is more or less the same.

As can be seen from the figure, the JavaScript engine in the browser is event-driven, and the events here can be regarded as various tasks assigned to it by the browser. These tasks can be derived from the code blocks currently executed by the JavaScript engine, such as calling setTimeout to add a task, or other threads from the browser kernel, such as interface element mouse click events, timing trigger time arrival notification, asynchronous request status change notification, and so on. From a code point of view, task entities are callback functions, and the JavaScript engine has been waiting for the arrival of tasks in the task queue. Because of the one-line relationship, these tasks have to be queued and processed by the engine one by one.

The t1-t2..tn above represents different time points, and the corresponding squares under tn represent tasks at that time. Suppose it is time T1 and the engine runs in the corresponding task box code of T1. At this point in time, let's describe the state of other threads in the browser kernel.

T1 moment:

GUI rendering thread:

This thread is responsible for rendering browser interface HTML elements and executes when the interface needs to be redrawn (Repaint) or reflow caused by some operation. Although this article focuses on explaining the JavaScript timing mechanism, it is necessary to talk about the rendering thread at this time, because the thread and the JavaScript engine thread are mutually exclusive, which is easy to understand, because the JavaScript script can manipulate DOM elements, and the element data obtained before and after the rendering thread may be inconsistent when modifying the attributes of these elements while rendering the interface.

While the JavaScript engine is running the script, the browser rendering thread is suspended, which means it is frozen.

Therefore, updating the interface in the script, such as adding nodes, deleting nodes or changing the appearance of nodes, will not be reflected immediately. These operations will be saved in a queue and will not have a chance to render until the JavaScript engine is idle.

GUI event trigger thread:

The execution of the JavaScript script does not affect the trigger of the html element event. In the T1 time period, the user first clicks a mouse button, and the click is captured by the browser event trigger thread to form a mouse click event. As can be seen from the figure, for the JavaScript engine thread, this event is transmitted asynchronously by other threads to the end of the task queue. Because the engine is processing the T1 task, the mouse click event is waiting to be processed.

Timed trigger thread:

Note that the browser model timing counter here is not counted by the JavaScript engine, because the JavaScript engine is single-threaded and cannot be counted if it is in a blocked thread state, it must rely on the outside to timing and trigger timing, so the timing events in the queue are also asynchronous events.

As can be seen from the figure, in this time period of T1, after the mouse click event is triggered, the previously set setTimeout timing has also arrived. for the JavaScript engine, the timing trigger thread generates an asynchronous timing event and puts it in the task queue, which is placed after the click event callback and waits for processing.

Similarly, also during the T1 period, a setInterval timer is added. Due to the interval timing, it is triggered twice in T1, and these two events are queued at the end of the queue to be processed.

It can be seen that if the time period T1 is very long, much larger than the timing interval of setInterval, then the timing trigger thread will continuously generate asynchronous timing events and put them at the end of the task queue, regardless of whether they have been processed or not, but once the tasks in front of T1 and the first timing events have been processed, the timing events in these arrangements will be executed uninterruptedly, because, for the JavaScript engine, Each task in the processing queue is handled in the same way, but in a different order.

After T1, that is, the task currently processed has been returned, the JavaScript engine will check the task queue and find that the current queue is not empty, then take out the corresponding task under T2 for execution, and so on at other times, and so on:

If the queue is not empty, the engine takes a task from the queue header until the task is processed, that is, the engine returns and then runs the next task, and the other tasks in the queue cannot be executed before the task returns.

I'm sure you already know whether JavaScript can be multithreaded and understand the running mechanism of JavaScript timers. Let's analyze some cases:

Case 1:setTimeout and setInterval

SetTimeout (function () {setTimeout (arguments.callee, 10);}, 10); setInterval (function () {}, 10)

The effect of these two pieces of code looks the same, but in fact, no. The setTimeout in the callback function in the first paragraph sets the new setTimeout timing after the JavaScript engine executes. Assuming that the last callback is processed to the next callback, it is assumed that the time interval between the two setTimeout callbacks is > = 10ms. In the second paragraph, after the timing is set by setInterval, the timing trigger thread will continuously generate asynchronous timing events every ten seconds and put them at the end of the task queue. Theoretically, there are two setInterval callback execution intervals.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report