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 their previous understanding is all wrong, hurriedly summed up.


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 around 1001ms, will certainly exceed 1000ms. In other words: The settimeout fails, the specified function is not executed after 500ms, but is deferred until 1000ms.


Look at the code again:

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

Running this script can be seen: Print 2 after printing 1, we specify 0ms inside the settimeout, we want to be able 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, which means you can't execute multiple pieces of code at the same time. The following explanation comes from this blog:

JavaScript is a single-threaded execution and cannot execute multiple pieces of code at the same time. When a piece of code is executing, all subsequent tasks must wait to form a queue. Once the current task is completed and the next task is removed from the queue, this is often referred to as "blocking execution." So a mouse click, or a timer arrives at a point in time, or an AJAX request is completed triggering a callback function that does not run immediately, but immediately queues up and executes as soon as the thread is idle. If the current JavaScript thread is executing a time-consuming code that has a mouse click, the event handler is blocked and the user is not immediately able to see the feedback, and the event handler is placed in the task queue until the previous code finishes and the execution begins. If a setTimeout is set in the code, then the browser will insert the code into the task queue at the appropriate time, and if the time is set to 0, it will immediately insert the queue, but not immediately, and still wait for the previous code to complete. So setTimeout does not guarantee that the execution time, whether timely execution depends on the JavaScript thread is congested or idle.


This means that settimeout can only guarantee that the task (functions that need to be executed) is inserted into the queue after the specified time, and that the task is not guaranteed to be executed at any time. The thread that executes the JavaScript takes the task out of the queue and executes it when it is idle. JavaScript gives us an illusion of asynchronous execution through this queuing mechanism.

var start = new Date (); SetTimeout (function () {    var end = new Date ();    Console.log ("Time Elapsed:", End-start, "MS"),}, and Console.log ("task finished.");
We feel that this code is executed asynchronously because the JavaScript thread is not blocking because of the time-consuming operation, so you can quickly take the task out of the queued queue and execute it.

Now that we know the principle of settimeout, let's look at the usage scenario 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 show the input in real time in <div> when the user enters a character in the text box. However, the actual effect is not so, it can be found that each time you press a character,,<div> can only display the previous content, unable to get the current character.


<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. In fact, there are 2 tasks involved, one is to write the keyboard input characters back into the input box, one is to get the value of the text box to write it into the Div. The first one is the default behavior of the browser itself, and one is the code we write ourselves. Obviously, you have to let the browser write the characters back to the text box before we can get its contents written to the Div. Change the order, which is exactly what settimeout (0) does.


Reference article: The role of setTimeout (0)


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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

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.