Home > Article > Web Front-end > Understand the setTimeout_javascript technique with a 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 has a biased understanding of this. In fact, it is not just a problem with IE, but a problem with the existing JavaScript engine's thread implementation (I don't have much concept about threads. If it is wrong, I hope readers can 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, focus and select it. Please click on each one now. You can see that 1 cannot be focused and selected, but 2 can. The difference between them is that when executing:
input.focus();
input.select();
, 2 has an additional setTimeout peripheral function with a delay time of 0, That is:
setTimeout(function(){
input.focus();
input.select();
}, 0);
Follow JavaScript: The Definitive Guide 5th 14.1 says:
In practice, setTimeout will tell the browser to enable the function registered within setTimeout after it has completed the execution of any event handlers for currently deferred events and updated the current state of the document.
Actually, this is a technique to jump out of the queue of tasks that need to be executed. Back to the previous example, when the JavaScript engine executes onkeypress, since there is no synchronized execution of multiple threads, it is impossible to process the focus and select events of the newly created element at the same time. Since these two events are not in the queue, after completing onkeypress, The JavaScript engine has discarded these two events, as you can see in Example 1. In Example 2, because setTimeout can jump tasks from a certain queue into a new queue, the expected results can be obtained.
This is the real purpose of setTimeout with a delayed event of 0. Here, you can take a look at Example 3. Its task is to update the entered text in real time. Please try it now. You will find that the preview area is always one beat behind. For example, when you enter a, a does not appear in the preview area. When b is entered, a appears calmly. In fact, we have a way to synchronize the preview area with the input box. I have not given an answer here, because the above is the solution, try it yourself!