SetTimeout in JavaScript: settimeout in js

Source: Internet
Author: User
Tags date1

SetTimeout in JavaScript: settimeout in js

1. setTimeout: single thread 

For a long time, we have been saying that Javascript is a single thread. No matter when the browser is running, there is only one thread running JavaScript programs.

However, I don't know if you have any questions. It's our setTimeout (like setInterval and Ajax) in the programming process. Isn't it asynchronous ?!!

For example:

<! DOCTYPE html> 

Run the code and open the chrome debugger. The result is as follows:


This result is easy to understand, because the content in setTimeout is executed after Ms. Of course, output a first, then Output c, Ms, and then output B in setTimeout.

Isn't Javascript a single thread? Isn't it a multi-thread ?!!

Actually, it's not. SetTimeout does not break the JavaScript single-thread mechanism. It is actually a single-thread.

In this case, you have to understand what is setTimeout.

See the following code to guess the result:

<! DOCTYPE html> 

After reading the above Code, guess what the output result is? 1000 ms?

Open the chrome debugger, see


Nana, why not 1000 milliseconds ?!!!

Let's look at the following code:

<! DOCTYPE html> 

After running the code!

Why is it that the browser is stuck and there is no alert !!

In principle, even if I have an infinite while LOOP, I need alert in 1 second.

All kinds of problems are caused by one reason,JavaScript is a single thread.

Remember that JavaScript is a single thread, and setTimeout does not implement multithreading. the truth behind it is as follows:

The JavaScript engine runs in a single thread. At any time, the browser only has one thread running JavaScript programs.

The browser kernel is multi-threaded, and they work together under the Internal Control to maintain synchronization. A browser must implement at least three resident threads: JavaScript Engine threads, GUI rendering threads, and browser event triggering threads.

* JavaScript EngineIt is based on the event-driven single-thread execution. the JavaScript engine keeps waiting for the arrival of tasks in the task queue and then processes them. At any time, the browser only has one JavaScript thread running the JavaScript program.

* GUI rendering threadResponsible for rendering the browser interface. When the interface needs to be repainted or a Reflow is triggered due to an operation, this thread will execute. However, you must note that the GUI rendering thread and the JavaScript engine are mutually exclusive. When the JavaScript engine is executed, the GUI thread will be suspended, the GUI update is immediately executed when the JavaScript engine is idle in a queue.

* Event-triggered threadWhen an event is triggered, the thread adds the event to the end of the queue to be processed, waiting for processing by the JavaScript engine. These events can come from the code blocks currently executed by the JavaScript engine, such as setTimeout, other threads from the browser kernel, such as mouse clicks and Ajax asynchronous requests, however, because of the JavaScript single-threaded relationship, all these events have to be queued for processing by the JavaScript engine (asynchronous code is executed only when no synchronous code is executed in the thread ).

So, through the above explanation, the above problems can be solved.

2. the latency of setTimeout is 0.

When the latency of setTimeout is 0, how can we execute it?

For example, the following code:

 <!DOCTYPE html> 

The result of running the code is as follows:


Suppose you already know how Javascript runs in a single thread. So there may be a question: the setTimeout time is 0 and is not added to the end of the processing queue. How can it be executed late? Shouldn't it be executed immediately?

In my understanding, even if the setTimeout time is 0, it is still setTimeout, And the principle remains unchanged. So it will be added to the end of the queue and executed in 0 seconds.

Moreover, after searching for information, it is found that setTimeout has a minimum execution time. When the specified time is earlier than this time, the browser uses the minimum allowed time as the setTimeout interval, that is to say, even if we set the number of milliseconds in setTimeout to 0, the called program is not started immediately.

What is the minimum interval?

This is related to browsers and operating systems. In John Resig's book "The Secret of Javascript ninja", we mentioned-Browsers all have a 10 ms minimum delay on OSX and a (approximately) 15 ms delay on Windows. (The minimum interval on an apple machine is 10 ms, and the minimum interval on a Windows system is about 15 ms). In addition, MDC also mentions the setTimeout introduction, the minimum interval (DOM_MIN_TIMEOUT_VALUE) defined in Firefox is 10 milliseconds, and the minimum interval defined in HTML5 is 4 milliseconds.

After talking about this, the latency of setTimeout is 0. It seems that it is meaningless. It is all executed after the queue.

No, it depends on how you use it. Place bricks in front of the jade.

1. You can use setTimeout to set the latency to 0 to simulate the animation effect.

For details, see the following code:

<! DOCTYPE html> 

Because it is an animation, I want to see its effect. Please check the official code.

In line 19th of the Code, after each render execution is completed (increasing height by 1) Using setTimeout, because Javascript is a single thread, in addition, the anonymous function in setTimeout will execute the render after the render is executed. Therefore, animation effects can be achieved.

2. You can use setTimeout to set the latency to 0 to capture events.

When we click a child element, we can use the setTimeout feature to simulate event capture.

See the following code:

<! DOCTYPE html> 

Run the code, click the Pink Square, and output the result:

3. setTimeout: this 

Speaking of this, the understanding of this is: this is the current object pointing to the function execution. If there is no clear current object, it is pointing to the window.

Well, let's take a look at the following code:

 <!DOCTYPE html> 

View the output result through the chrome Debugger:

Outputs, how does it output "!!" What about it? Shouldn't it be the "monkey" in obj ?!!

This is because this in the function executed in setTimeout always points to the window.

No, so how does this. print in setTimeout (this. print, 1000) point to obj in the above Code ?!!

Note: Here I am talking about "this in the delayed execution function", rather than this in the setTimeout call environment.

What does it mean? 

SetTimeout (this. print, 1000). this in this. print is in the call environment;

And this. print = function () {console. log (this. name) ;}, this anonymous function is the setTimeout delayed execution function, where this. name indicates this in the delayed execution function.

Hey, you understand.

Var age = 24; function Fn () {this. age = 18; setTimeout (function () {// this indicates window console. log (this); // output 24 instead of the 18 console of Fn. log (this. age);}, 1000);} new Fn ();

Else, there is a question. For example, I want to point this in the setTimeout delayed execution function to the called function, rather than the window ?!! What should we do.

The common method is to use that.


Yes, that. With the knowledge of closures, you want to make sure that you pass in this.

For details, see:

Var age = 24; function Fn () {// that var that = this; this. age = 18; setTimeout (function () {console. log (that); console. log (that. age);}, 1000);} new Fn ();

Another method is to use bind.

As follows:

Var age = 24; function Fn () {this. age = 18; // bind input this setTimeout (function () {console. log (this); console. log (this. age );}. bind (this), 1000);} new Fn ();

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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: 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.