Does JavaScript really have to be asynchronous? and see the principle of settimeout and the use of settimeout (0)

Source: Internet
Author: User

Before today I always thought settimeout This function is asynchronous, inadvertently saw an article about settimeout. found that they once knew all is wrong, hurriedly summarizes under.


Look at the code first:

var start = new Date (); SetTimeout (function () {    var end = new Date ();    Console.log ("Time Elapsed:", End-start, "MS"),}, and (new Date-start <= 1000) {}

Running this script can be seen: the value of time elapsed about 1001ms, will certainly exceed 1000ms. That is: The settimeout fails, and the specified function does not run after 500ms. Instead, it is delayed to 1000ms before it runs.


Look at the code again:

function A () {SetTimeout (function () {console.log (1);},0); Console.log (2);} A ();

The execution of this script can be seen: Print 2 after printing 1, we have specified in the settimeout 0ms, we hope to execute immediately, but actually no effect.


To understand the above 2 pieces of code, we need to look at how settimeout is implemented in JavaScript. One thing to keep in mind: JavaScript is single-threaded, that is, you can't run multiple pieces of code at the same time.

The following explanation comes from this blog:

JavaScript is a single-threaded operation and cannot run multiple pieces of code at the same time. When a piece of code is running, all of the tasks that might be required to wait, form a queue.

Once the current task has finished running, the next task is removed from the queue, which is often referred to as a "plug-in Run". So a single mouse click, or a timer arrives at a point in time, or an AJAX request is completed triggering a callback function. These event handlers or callback functions do not run immediately, but are queued immediately. Once the thread has spare, it runs. If the current JavaScript thread is running a very time-consuming code, a mouse click occurs at this point. Then the event handler is blocked. The user is not immediately able to see the feedback. The event handler is put into the task queue. It will not start until the previous code finishes. Suppose a setTimeout is set in the code, then the browser will be at the right time. Insert code into the task queue. Assuming this time is set to 0, it means inserting the queue immediately, but not running immediately. You still have to wait for the previous code to complete.

So setTimeout does not guarantee the running time. Whether the JavaScript thread is busy or spare depends on the time it runs.


This means that settimeout only guarantees that the task (functions that need to be run) is inserted into the queue after a specified period of time and does not guarantee when the task will run. The thread running JavaScript will take the task out of the queue and run it on its own when spare. JavaScript through such a queue mechanism. Give us an illusion of running asynchronously.

var start = new Date (); SetTimeout (function () {    var end = new Date ();    Console.log ("Time Elapsed:", End-start, "MS"),}, and Console.log ("task finished.");
The reason we feel this code is running asynchronously is that the JavaScript thread is not blocked by any time-consuming operation, so it can take the task out of the queued queue very quickly and run it.

Now that we know the principle of settimeout, now look at the use of settimeout (0). The following example is from this article.

<input type= "text" onkeydown= "Show (This.value)" ><div></div><script type= "Text/javascript" >  function Show (val) {    document.getelementsbytagname (' div ') [0].innerhtml = val;  } </script>
This binds the KeyDown event, which is intended to be when the user enters characters in the text box. Displays the input content in real time in <div>. But the actual effect is not so, can be found. Each time a character is pressed, only the previous content can be displayed in,<div>, and the current character cannot be obtained.


<input type= "text" onkeydown= "var self=this; SetTimeout (function () {Show (Self.value)}, 0) "><div></div><script type=" Text/javascript ">  function Show (val) {    document.getelementsbytagname (' div ') [0].innerhtml = val;  } </script>

This code uses the settimeout (0) to achieve the desired effect.

There are actually 2 tasks involved, one of which is to write back the characters entered in the keyboard into the input box. One is to get the value of the text box to write it to the Div. The first one is the default behavior of the browser itself. One is the code we write ourselves. Very clearly. It is necessary to have the browser write the characters back to the text box first. Then we have the ability to get its contents written into the div. Change the order, which is exactly what settimeout (0) does.


Article: The role of setTimeout (0)


Is the

JavaScript really asynchronous? and see the implementation of SetTimeout and settimeout (0) The use of the scene

Related Article

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.