SoFunction
Updated on 2025-03-06

Recognize setTimeout with delay time of 0

Let's take a look at my previous article: 9 pitfalls and comments on JavaScript, the issues mentioned in Point 9 Focus Pocus. The original author's deviation in understanding this is actually not just an IE issue, but a problem with the existing JavaScript engine for thread implementation (I don't have many concepts about threads. If it is not right, I hope readers will give me some advice). .Let’s look at 1 and 2. If you can look at the source code, you will find that our task is very simple, which is to add an input text box to the document and focus and select it. Please click it separately now and you can see that 1 is not able to focus and select, while 2 is OK. The difference between them is that in the execution:

();
();
When   2 has an additional peripheral function of setTimeout with a delay time of 0, i.e.:

setTimeout(function(){
 ();
 ();
}, 0);
According to JavaScript: The Definitive Guide 5th 14.1:

In practice, setTimeout will tell the browser to enable the registered function in setTimeout after it completes the execution of the event processor that has delayed the event and completes the current status update of the document.

Actually, this is a skill to jump out of the queue of tasks that need to be executed. Going back to the previous example, when the JavaScript engine executes onkeypress, it is impossible to handle the focus and select events that just created the element at the same time because there is no synchronous execution of multiple threads. Since both events are not in the queue, after completing onkeypress, the JavaScript engine has discarded these two events, as you saw in Example 1. In Example 2, since setTimeout can jump from a queue to a new queue, the desired result can be obtained.

This is the real purpose of setTimeout with delayed event of 0. Here, you can take a look at Example 3. Its task is to update the input text in real time. Please try now. You will find that the preview area is always a beat behind. For example, if you enter a, the preview area does not appear. When you enter b, a appears calmly. In fact, we have a way to make the preview area synchronously with the input box. I did not give the answer here, because what is mentioned above is the solution idea, try it yourself!