SetTimeout you don't know.

Source: Internet
Author: User
Tags date object bind execution split thread time interval window

See a good article "you will use SetTimeout", reprinted over, changed a name, suddenly feel big, quack.

Added a few small knowledge about settimeout and setinterval:

About SetInterval () and settimeout () return values

SetInterval (), settimeout () returns a value that is generally considered to be an ID, passing this ID value to Clearinterval (), cleartimeout () can cancel execution, for example:

var intervaltimer=setinterval (function () {

Console.log (1)

},3000);

Console.log (Intervaltimer); It's usually a number.

Button.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 point in the first parameter function points to the Window object, which is related to the scope of the variable:

var a=1;

var obj={

A:2,

B:function () {

settimeout (function () {

Console.log (THIS.A);//Here The return is: 1;

},2000);

}

};

OBJ.B ();

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

var a=1;

var obj={

A:2,

B:function () {

settimeout (function () {

Console.log (THIS.A);//Here The return is: 2;

}.bind (this), 2000);/Note this line

}

};

OBJ.B ();

For the Bind () method, you can look here: http://www.css88.com/archives/5611

About the parameters of setinterval () and settimeout ()

We all know that setinterval () and settimeout () can receive two parameters, the first parameter is the function that needs callback, the parameter that must be passed in, the second parameter is the time interval, the number of milliseconds, can omit, this can see the article below,

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 narrowed down 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 saying that setinterval () and settimeout () can receive more parameters, so what are these parameters for? Starts with the third argument, which is used to represent the parameters passed in by the first parameter (the callback function), for example:

settimeout (function (a,b) {

Console.log (1+a+b);//Printed here are: 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 () Perform.

var intervaltimer=setinterval (function () {

Console.log (1)

},3000);

Console.log (Intervaltimer);

Button.onclick=function () {

Cleartimeout (Intervaltimer); Look here, it's not clearinterval.

};

=============== The following sources: Can you use settimeout? ===================

The settimeout in 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 Application Scenarios

Timer, Carousel graph, animation effect, automatic scrolling, etc.

Some of the above should be settimeout in the hearts of everyone, because we usually use is not much.

But is settimeout really that simple?

Test questions

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

var starttime = new Date ();

settimeout (function () {

Console.log (New Date ()-starttime);

}, 100)

How much is the final print, please?

I think the correct answer is, depending on how much time it takes for the JS to run synchronously.

MAX (Synchronous execution time, 100).

Add one more topic, only the following code

settimeout (function () {

Func1 ();

}, 0)

Func2 ();

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

This answer should be relatively simple, func2 first, func1 after execution.

One more question.

settimeout (function () {

Func1 ()

}, 0)

And

settimeout (function () {

Func1 ()

})

What's the difference?

0-second delay, this callback will be placed in a time period that can be executed immediately to trigger. The JavaScript code is mostly Top-down, but with asynchronous code such as Dom rendering, event response, and so on, they will form a queue, and a 0-second delay will be done.

Do not write 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 narrowed down to the minimum time interval, Safari,chrome,opera is more 10ms up and down.

The above answer comes from the JavaScript frame design

OK, look at the above several topics is not feel settimeout not imagined that.

SetTimeout and Single Thread

Here are some of my own understanding

The first thing to note is that JavaScript is single-threaded, and is characterized by easy blocking. If a program is processed for a long time, it can easily cause the entire page to hold. What can we do with any interaction?

Simplification of complexity? Complex logic back-end processing? HTML5 of multithreading?

It's all OK, but settimeout is also a brilliant at publicity to deal with the problem.

A key use of settimeout is fragmentation, and if a program is too large, we can split it into small chunks.

For example, in the case above, we split the complex logic into a fragment and put it into the queue. In this way, even when the complex program is not finished, we can get even the response if we manipulate the page. In fact, the interaction is inserted into a complex program to execute.

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

There is a function library Concurrent.Thread.js is to achieve the multithreading of JS.

An example of a simple use, after the introduction of Concurrent.Thread.js

Concurrent.Thread.create (function () {

for (var i = 0;i<1000000;i++) {

Console.log (i);

};

});

$ (' #test '). Click (function () {

Alert (1);

});

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

Is it very bad ~

There is also a scenario, when we need to render a very complex DOM, such as table components, complex composition, and so on, if the whole process requires 3s, we are waiting for the complete process to complete the rendering, or use a settimeout fragmentation, the content of a piece of intermittent rendering.

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

How to use

SetTimeout is so powerful, do we need to use it heavily in the project?

My point of view is very not recommended, in our business, basically prohibit the use of settimeout in the business logic, because I see a lot of ways to use the problem is difficult to solve, settimeout as a hack way.

For example, we use this instance before an instance is initialized, and the wrong solution is to use an instance with a settimeout to ensure that the instance is initialized first.

Why the mistake? This is actually the way to use hack.

The first is to bury the pit, disrupting the life cycle of the module

Second, when problems arise, settimeout is actually difficult to debug.

I think the right way to use it is to look at the lifecycle (refer to the lifecycle of the software) and take the instantiation to the pre-use execution.

In summary, settimeout actually want to use good or very difficult, he more appeared in the Framework and class library, such as some implementation of Promis framework, on the use of the settimeout to achieve asynchronous.

So if you want to read some source code and want to build some wheels, settimeout is still an essential tool.



Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.