The things that settimeout in JavaScript _javascript skills

Source: Internet
Author: User
Tags date1

One, settimeout those things of the single thread

All along, everyone is saying that JavaScript is single-threaded, and that browsers are running JavaScript programs whenever and only one thread.

However, do not know that there is no question--that is, we are in the programming process of the settimeout (similar to the setinterval, Ajax), not asynchronous execution?!!

For example:

 <! DOCTYPE html>
  
 

Run the code, open the Chrome debugger, and get the following results

This result is very easy to understand, because I settimeout content in 100ms after the implementation of it, of course, first output a, and then output c,100ms and then output settimeout in the B.

Gee, that JavaScript is not a single thread, this can not be implemented multithreading?!!

Actually, it's not. SetTimeout does not break JavaScript's single-threaded mechanism, it's actually a single-threaded process.

Why do you say that, then you have to understand settimeout is what is going on.

Take a look at the code below and guess the result:

 <! DOCTYPE html>
  
 

Look at the above code, guess what the output results? 1000 milliseconds?

Let's Open the Chrome debugger, see figure below


Nani, why not 1000 milliseconds?!!!

Let's look at the following code:

 <! DOCTYPE html>
  
 

After running the code!

How to keep refreshing, browser card dead, and no alert!!

According to the truth, even if I am infinite loop, in 1 seconds after the alert ah.

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

To remember that JavaScript is single-threaded, settimeout does not implement multithreading, the truth behind it is such a drop:

JavaScript engines are single-threaded, and browsers run JavaScript programs whenever and only one thread.

The browser's kernel is multi-threaded, they work together under the control of the kernel to keep synchronization, and a browser implements at least three resident threads: JavaScript engine thread, GUI rendering thread, browser event triggering thread.

The *javascript engine is executed on an event-driven single-threaded basis, and the JavaScript engine waits for tasks in the task queue to come along and process them, Browsers run JavaScript programs whenever there is only one JavaScript thread.

The *gui rendering thread is responsible for rendering the browser interface, which is executed when the interface needs to be redrawn (Repaint) or because of an operation that causes reflux (reflow). Note, however, that the GUI rendering thread is mutually exclusive to the JavaScript engine, and that when the JavaScript engine executes, the GUI thread is suspended and the GUI update is saved in a queue until the JavaScript engine is idle and executed immediately.

* Event triggers a thread that, when triggered, adds an event to the tail of the queue to be processed, waiting for the JavaScript engine to process it. These events can come from code blocks currently executing by the JavaScript engine such as settimeout, other threads from the browser kernel such as mouse clicks, Ajax asynchronous requests, etc. However, because of the single-threaded relationship of JavaScript, all of these events have to be queued for JavaScript engine processing (asynchronous code executes without any synchronization code being executed in the thread).

So, through the above explanation, all the above problems solved.

Second, the settimeout of those things the delay time is 0

When the settimeout delay time is 0 o'clock, how do you think it will execute?

For example, the following code:

 <! DOCTYPE html>
  
 

The results of the run code are as follows:

Let's say you already know how JavaScript works in a single thread. So, there may be such a question: The settimeout time is 0, did not add to the end of the processing queue, how late to execute it? Should it not be done immediately?

My understanding is that even if the settimeout time is 0, but it is still settimeout ah, the principle is unchanged. So it will be added to the end of the queue and executed after 0 seconds.

Moreover, after finding data, settimeout has a minimum execution time, and when the specified time is less than that time, the browser uses the minimum allowable time as the settimeout interval, which means that even if we set the settimeout number to 0, The invoked program also does not start immediately.

How much is the minimum time interval?

This is related to the browser and the operating system. In John Resig's book "The Secret of JavaScript ninja", –browsers all have a 10ms minimum delay on OS X and a (approximately) 15ms delay on Window S. (The minimum time interval on the Apple machine is 10 milliseconds, the minimum time interval on the Windows system is approximately 15 milliseconds), and the minimum time interval defined in Firefox is also mentioned in the MDC's introduction to SetTimeout (Dom_min_timeout_ VALUE) is 10 milliseconds, and the minimum time interval defined by HTML5 is 4 milliseconds.

Having said so much, SetTimeout's delay time is 0, it doesn't seem to make sense, it's all done in the queue.

Not also, born my material will be useful, depends on how you use it. Throw bricks under the jade.

1, can use the SetTimeout delay time is 0, simulates the animation effect Oh.

For more information, see the following code:

 <! DOCTYPE html>  
 

Because it is animation, so want to see its effect, but also please reader run the code OH.

In line 19th of the code, with SetTimeout, after each render execution completes (increments by 1), the JavaScript is single-threaded and the anonymous function in settimeout executes render after the render execution completes. So you can achieve animation effect.

2, can use the SetTimeout delay time is 0, realizes catches the event oh.

When we click on the child element, we can use the settimeout feature to simulate the capture event.

Please see the following code:

 <! DOCTYPE html>  
 

Execute code, click on the pink square, output the result:

Iii. The settimeout of those things

Speaking of this, it is understood that this is the current object that points to the execution of the function, and it points to window if there is no explicit current object.

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

 <! DOCTYPE html>
  
 

View the output through the Chrome debugger:


Hey, how does it output "!!"? It? Should not be the "monkey" in obj?!!

This is because this in the function that is being executed in settimeout always points to window.

No, how does this.print in the settimeout (this.print,1000) in the above code point to obj?!!

Note Oh, I'm talking about "this in deferred execution function", not the settimeout in the calling environment.

What do you mean?

settimeout (this.print,1000), where this is the this.print in the calling environment;

and This.print=function () {console.log (this.name);}, this anonymous function is the settimeout deferred execution function, where the this.name is the delay in executing this in the function.

Hey, that's clear.

 var age =;
function Fn () {
 this.age =;
 settimeout (function () {
  //this represents window
  Console.log (this);
  Output 24 Instead of FN
  Console.log (this.age);
 },1000);
}
New Fn (); 

Well, there's a question, for instance, I want to delay the execution of this in the settimeout to the calling function, not the window?!! What should we do?

The common method is to use that.

That?

Yes, that. With the knowledge of closures, let that be the guarantee that you pass in this, which is what you want.

See below for details:

 var age =;
function Fn () {
 //that in this
 var. = this;
 This.age =;
 settimeout (function () {
  console.log (that);
  Console.log (that.age);
 },1000);
}
New Fn (); 

One other way is to use bind.

As follows:

 var age =;
function Fn () {
 this.age =;
 Bind incoming this
 settimeout (function () {
  console.log (this);
  Console.log (this.age);
 Bind (this), 1000);
New Fn ();

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.