The role of settimeout delay 0 milliseconds in JS

Source: Internet
Author: User

Often see settimeout delay 0ms JavaScript code, feel very confused, is it not a delay of 0ms and no delay is not a reason? Later through the investigation of data and experiments to obtain the following two roles, may also have a role I do not know, hope to know that friends in the comments on the back of the generous point.
1, realize the asynchronous JavaScript;
JavaScript is normally executed in sequence. However, we may let the statement after the statement execution itself, then we can use the settimeout delay 0ms to achieve.
Such as:
Alert (1);
SetTimeout ("Alert (2)", 0);
Alert (3);
Although the delay is 0ms, but the order of execution is: 1,3,2
This ensures that the statements inside the settimeout are executed at the end of a code segment.


2. In the event, SetTimeout will tell the browser to enable the function 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. ;
For example, if an event creates a text box on a page and assigns a value to the text box (completing the current state of the document), then the focus is on the text box, and the contents of the text box are selected (the SetTimeout delay 0MS implementation is required later, otherwise it is not possible).

Look at an example:

<!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD"><HTML><Head>    <MetaCharSet= "Utf-8">    <title>SetTimeout</title>    <Scripttype= "Text/javascript" >        (function(){            functionget (ID) {returndocument.getElementById (ID); } window.onload= function() {Get ('Makeinput'). onmousedown= function(){                    varinput=Document.createelement ('input'); Input.setattribute ('type', 'text'); Input.setattribute ('value', 'test1'); Get ('Inpwrapper'). appendchild (input);                    Input.focus ();                Input.select (); } Get ('Makeinput2'). onmousedown= function(){                    varinput=Document.createelement ('input'); Input.setattribute ('type', 'text'); Input.setattribute ('value', 'test1'); Get ('Inpwrapper2'). appendchild (input); SetTimeout (function() {input.focus ();                    Input.select (); }, 0); } Get ('INPUT1'). onkeypress= function() {Get ('Preview1'). InnerHTML=  This. Value; } Get ('Input2'). onkeypress= function() {setTimeout (function() {Get ('Preview2'). InnerHTML=Get ('Input2'). Value; },0 );    }            }        })(); </Script></Head><Body><H1><Code>DEMO1</Code></H1><H2>1, not used<Code>SetTimeout</Code>(text box content is not selected)</H2><ButtonID= "Makeinput">Generate input</Button><PID= "Inpwrapper"></P><H2>1. function<Code>SetTimeout</Code>(Check text box contents now)</H2><ButtonID= "Makeinput2">Generate input</Button></H2><PID= "Inpwrapper2"></P>--------------------------------------------------------------------------<H1><Code>DEMO2</Code></H1><H2>1, not used<Code>SetTimeout</Code>(Only the second character is entered, the previous word characters shown)</H2><inputtype= "text"ID= "INPUT1"value=""/><DivID= "Preview1"></Div><H2>1. function<Code>SetTimeout</Code>(characters are displayed at the same time as input)</H2><inputtype= "text"ID= "Input2"value=""/><DivID= "Preview2"></Div></Body></HTML>

The existing JavaScript engine is a single-threaded processing task. It puts the task in the queue, does not synchronize, and must complete a task before starting another task.

In DEMO1, when the JavaScript engine executes onmousedown, it executes alert (123) and then executes select and focus calls, because no DOM element is created at this time, the desired result is not obtained, and then the create operation is performed. Conversely, if we change the execution order of the call, the "execute first" element is created, and then the select and focus calls are performed using settimeout delay of 0 milliseconds. The core is to add the select and focus calls to the task queue, and then "perform the task immediately" after emptying the call stack.

The role of settimeout delay 0 milliseconds in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.