The settimeout that you don't know

Source: Internet
Author: User

The settimeout you don't know about SetInterval () and settimeout () return values

SetInterval (), SetTimeout () returns a value that is generally considered an ID, passes this ID value to Clearinterval (), and cleartimeout () can cancel execution, for example:

12345678 varintervalTimer = setInterval(function() {    console.log(1)},3000);console.log(intervalTimer); //一般是一个数字,Numberbutton.onclick = function() {    clearInterval(intervalTimer);};
About this in the callback function in SetInterval () and settimeout ()

SetInterval (), the SetTimeout () method is provided by the browser window object, so this in the first argument function points to the Window object, which is related to the scope of the variable:

1234567891011 vara = 1;varobj = {    a: 2,    b: function() {        setTimeout(function() {            console.log(this.a); //这里返回的是:1;        },        2000);    }};obj.b();

Of course you can change the situation by using the bind () method:

12345678910 vara = 1;varobj = {    a: 2,    b: function() {        setTimeout(function() {            console.log(this.a); //这里返回的是:2;        }.bind(this), 2000); //注意这行    }};obj.b();

For the Bind () method, you can see here: http://helloweb.wang/qianduankaifa/Js%20JQuery/2015-12-06/403.html

About parameters for SetInterval () and settimeout ()

We all know that setinterval () and settimeout () can receive two parameters, the first parameter is a function that needs a callback, the parameter must be passed in, the second parameter is the time interval, the number of milliseconds, can be omitted, this can be seen below the article, do not pass the second parameter, browser automatic configuration time , in the Ie,firefox, the first match may give a very large number, 100ms up and down, will be reduced to the minimum time interval, Safari,chrome,opera is more than 10ms up and down.

But what I'm going to say is not this, I'm going to say that setinterval () and settimeout () can receive more parameters, so what are these parameters for? Start with the third argument, which in turn represents the parameter passed in by the first parameter (callback function), for example:

123 setTimeout(function(a,b){    console.log(1+a+b);//这里打印的是:8},1000,3,4);

Of course some old browsers are not supported.

About Clearinterval () and cleartimeout ()

Clearinterval () and cleartimeout () are actually generic, that is, you can cancel SetTimeout () execution with Clearinterval (), cleartimeout () can also cancel   SetInterval () execution.

12345678 varintervalTimer = setInterval(function() {    console.log(1)},3000);console.log(intervalTimer);button.onclick = function() {    clearTimeout(intervalTimer); //注意这里,不是clearInterval哦};
The settimeout inside the textbook

The definition is simple.

The SetTimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds.

Wide range of applications: Timers, Carousel charts, animation effects, auto scrolling, etc.

Some of the above should be settimeout in the hearts of everyone, because we do not use a lot of common.

But is settimeout really that simple?

Test questions

A topic, if you find the following in a piece of code

1234 varstartTime = new Date();setTimeout(function () {        console.log(newDate() - startTime);}, 100)

How much is the last print, please?

I think the correct answer is that it depends on how much time it takes to execute the JS synchronously.

MAX (Time for synchronous execution, 100).

Add one more question, only the following code

1234 setTimeout(function() {    func1();}, 0)func2();

Func1 and Func2, who's going to do it first?

The answer should be simple, func2 first, func1 behind.

One more question.

123 setTimeout(function() {        func1()}, 0)

And

123 setTimeout(function() {        func1()})

What's the difference?

0 seconds delay, this callback will be placed in an immediate execution of the time period to trigger. The JavaScript code is mostly top-down, but with asynchronous code about DOM rendering, event response, and so on, they will form a queue, and a 0-second delay will implement queue-jumping operations.

Do not write the second parameter, the browser automatically configure the time, in the Ie,firefox, the first match may give a very large number, 100ms up and down, will be reduced to the minimum time interval, Safari,chrome,opera is more than 10ms up and down.

The above answer comes from the JavaScript framework design

Well, look at the above several topics is not feeling settimeout not imagined.

SetTimeout and Single Thread

Here are some of my own understanding:

The first thing to note is that JavaScript is single-threaded and is prone to blocking. If a program takes a long time to process, it can easily cause the entire page to hold. What can I do with any interaction?

Simplification of complexity? Complex logical back-end processing? HTML5 multi-threaded?

The above is OK, but settimeout is also the hooping to deal with this problem.

SetTimeout A key usage is sharding, and if a program is too large, we can split it into small chunks.

For example, in the above case, we divide the complex logic into the processing, and the shards are plugged into the queue. This way, even when the complex program is not finished, we can also get a response if we manipulate the page. The fact is that the interaction is inserted into the complex program execution.

Another way of thinking, above is to use settimeout to implement a pseudo-multithreading concept.

There is a function library Concurrent.Thread.js is to implement the multi-threaded JS.

An example of simple use, after introducing Concurrent.Thread.js

12345678 concurrent.thread.create ( function ()  { &NBSP;&NBSP;&NBSP;&NBSP; for   ( var  < Code class= "JS Plain" >i = 0; i < 1000000; i++)  { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; console.log (i); &NBSP;&NBSP;&NBSP;&NBSP; $ ( ' #test ' Code class= "JS keyword" >function ()  {       alert (1);

Although there is a huge loop, it does not prevent you from triggering alert ();

is not very powerful ~

There is also a scenario where we need to render a very complex DOM, such as a table component, complex composition, and so on, if the entire process requires 3s, we are waiting for the complete processing to complete in the rendering, or use a settimeout shard, the content of a piece of intermittent rendering.

In fact, SetTimeout gives us a lot of space to optimize the interaction.

The settimeout that you don't know

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.