1. What should I do if I want to delay a certain time before executing a JS function?
Answer: "SetTimeout (' Update () ', 1000);"
where the update () function is the function that executes after the delay, the time unit behind is Ms.
Example one:
<Scriptlanguage= "JavaScript"> vari;//10th line of codeSetTimeout ("ABC ()", the); functionABC () {//The 11th line of code will all be placed in this function.Alert (1); }</Script>
Example two:
<Script>varI=1;varTimeid=NULL;functiondisplay () {Timeid=Window.setinterval ("delay ()", +);}functiondelay () {if(i<Ten) {alert (i); I++; } Else{window.clearinterval (Timeid); }}display ();</Script>
If you can look at the source code, you will find our task is simple, is to add an input text box to the document, and focus and select. Please click now and you can see that 1 is not able to focus and select, and 2 can. The difference between them is that in executing
Input.focus ();
Input.select ();
, a peripheral function of setTimeout with a delay time of 0 is more than 2, i.e.:
SetTimeout (function () {
Input.focus ();
Input.select ();
}, 0);
According to the Javascript:the definitive guide 5th 14.1 said:
In practice, SetTimeout will tell the browser to enable functions registered within SetTimeout after it completes the execution of the event handler for any current delay event and completes the current status update of the document.
In fact, this is a trick to jump off a queue of tasks that need to be performed. Back in the previous example, when the JavaScript engine was executing onkeypress, it was not possible to process the focus and select events of the element just created at the same time because there was no multi-threaded synchronous execution, and since both events were not in the queue, after the onkeypress was completed, The JavaScript engine has discarded both events, as you can see in case 1. In Example 2, because settimeout can jump a task from one queue to a new queue, it gets the desired result.
This is the real purpose of the settimeout with a delay 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 behind a beat, such as you lose A, the preview area does not appear a, immediately after the input B, a is not leisurely to appear. In fact, we have a way to let the preview area with the input box in sync, I did not give an answer, because above, is to solve the idea
JS Setting the delay Time function