Let's take a look at my previous Article : The Nine traps and comments of JavaScript, which were mentioned in focus poocus. The original author's understanding of this is biased, not just the issue of IE, but the issue of thread implementation by the existing JavaScript Engine (I don't have many concepts about threads, if not, hope you can advise me a lot ).. Let's look at 1 and 2. If you can see Source code , We will find that our task is very simple, is to add an input text box to the document, and focus and select. Click here. We can see that 1 cannot be focused or selected, and 2 can. The difference between them is that in execution:
Input. Focus ();
Input. Select ();
2 has an extra setTimeout function with a delay of 0, namely:
SetTimeout (function (){
Input. Focus ();
Input. Select ();
}, 0 );
According to section 14.1 In javascript: the definitive guide 5th:
In practice, setTimeout tells the browser to enable the setTimeout Function after it completes execution of the event processor for any current delay event and updates the current state of the document.
In fact, this is a technique for skipping the tasks to be executed from the queue. Back to the previous example, when the JavaScript engine executes onkeypress, because there is no multi-thread synchronous execution, it is impossible to simultaneously process the focus and select events of the newly created element, since neither of these events is in the queue, the JavaScript engine has discarded these two events after onkeypress is completed, as you can see in Example 1. In Example 2, because setTimeout can switch tasks from a queue to a new queue, expected results can be obtained.
This is the real purpose of setTimeout with a latency event of 0. Here, you can take a look at example 3. Its task is to update the input text in real time. Now try it. You will find that the preview area is always lagging behind. For example, if you lose, A does not appear in the preview area. When B is entered immediately, A does not appear in a hurry. In fact, we have a way to synchronize the preview area with the input box. I didn't give an answer here, because what we mentioned above is a solution. Try it yourself!