What is a function throttling?
function throttling simply does not want the function to be invoked continuously for a short period of time. For example, our most common is when the window zoom, often perform some other operation functions, such as sending an AJAX request, etc., then the window scaling, it is possible to send multiple requests continuously, This is not what we want, or our common mouse move out of the tab switch effect, sometimes continuous and moving quickly, there will be flashing effect, this time we can use function throttling to operate. As you all know, DOM operations can be very consuming or impacting performance, if it is said that in the window scaling, the element binding a large number of DOM operations, will trigger a large number of consecutive computations, such as in IE, too much DOM operation will affect browser performance, or even serious circumstances, will cause the browser crash occurred. This time we can use function throttling to optimize the code ~
The basic principle of function throttling:
Using a timer, delay the execution of the function, such as using settomeout () to delay the execution of the function after a period of time, if other events are triggered during that time period, we can use the Purge method Cleartimeout () to clear the timer, and then settimeout () A new timer is delayed for a while to execute.
Recently engaged in a project with a team, there is a page that uses the traditional pattern development (spit It why not react), its DOM operation is more, then the performance is poorer, especially when you zoom the window, the terrible things happen, there are cotton, even the browser paralyzed. Why, then?
Because the DOM operation of this page is very much, the window zooms every frame to trigger function execution, successive DOM operation, so the overhead of the browser is very big. Since the browser will recalculate the DOM while zooming in the window, why can't we let the DOM compute the delay, so that the window stops zooming before it is recalculated, which saves the browser overhead and optimizes the effect?
Knowledge Preparation
1. settimeout (CODE,MILLISEC) is certainly the protagonist of this article.
The settimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds.
Code required. The JavaScript code string to execute after the function to be invoked.
Millisec required. The number of milliseconds to wait before executing the code.
Tip: settimeout () executes only one code at a time. If you want to call more than once, use SetInterval () or let code itself call SetTimeout () again.
Widely used in timers, carousel maps, animation effects, automatic scrolling and so on.
2. Cleartimeout (Id_of_settimeout)
Parameter id_of_settimeout the ID value returned by settimeout (). This value identifies the block of deferred execution code to be canceled.
3. Fun.apply (thisarg[, Argsarray])
The Apply () method calls a function when it specifies the this value and parameters (arguments are in the form of an array or class array object)
The syntax of the function is almost the same as the call () method, except that the call () method accepts a list of arguments, and apply () accepts a (or class array object) that contains multiple parameter arrays.
Parameters
Thisarg
The This value specified when the fun function is run. It is important to note that the specified this value is not necessarily the true this value when the function is executed, and if the function is in a non strict mode, the specified null or undefined automatically points to the global object (the browser is the Window object), and the value is the original value (number, String, Boolean value) points to the automatic wrapper object for the original value.
Argsarray
An array or class array object in which the array elements are passed as separate arguments to the fun function. If the value of the parameter is null or undefined, no arguments need to be passed in. Class array objects can be used starting from ECMAScript 5.
When you call an existing function, you can specify a this object for it. This refers to the current object, which is the object that is calling this function. With apply, you can write this method only once and then inherit it from another object without having to repeat the method in the new object.
4. Fun.call (thisarg[, arg1[, arg2[, ...)]]
The method invokes a function or method with a specified this value and several specified parameter values.
Parameters
Thisarg
The This value specified when the fun function is run. Note that the specified this value is not necessarily the true this value when the function is executed, and if the function is in a non strict mode, the this value specified as null and undefined automatically points to the global object (the browser is the Window object), and the value is the original value (the number , String, Boolean), this will point to the automatic wrapper object for the original value.
Arg1, Arg2, ...
The specified argument list.
When you call a function, you can assign a different this object. This refers to the current object, the first parameter of the call method. With the call method, you can borrow a method from another object on one object, such as Object.prototype.toString.call ([]), or an array object borrows the method on the object.
Role:
Calling the parent constructor using the call method
Calling anonymous functions using the call method
Calls the anonymous function using the call method and specifies the ' this ' of the context
Here is a digression:
Apply is very similar to call (), except in the way that you provide parameters. Apply uses a parameter array instead of a set of argument lists. Apply can use an array literal (literal), such as fun.apply (this, [' Eat ', ' bananas ']), or an array object, such as fun.apply (this, new array (' eat ', ' bananas ') ))。 You can also use the arguments object as a Argsarray parameter. Arguments is a local variable of a function. It can be used as all unspecified parameters of the invoked object. In this way, you do not need to know all the parameters of the invoked object when you use the Apply function. You can use arguments to pass all parameters to the called object. The invoked object is then responsible for handling these parameters.
Starting with the 5th edition of ECMAScript, you can use any kind of class array object, that is, an integer property with a length property and a range of [0...length]. For example, you can now use NodeList or an object of your own definition similar to {' Length ': 2, ' 0 ': ' Eat ', ' 1 ': ' Bananas '}.
Call, apply method The difference is that, starting with the second argument, the calling method parameter is passed to the borrowed method as an argument, and apply directly places the parameters in an array and then passes the argument list of the last borrowed method.
Application scenario: Call can be used when the parameter is clear, apply to arguments when the parameter is ambiguous
Now let's give an example
As is known to all, onscolll,onresize and so on are very performance-intensive, printing numbers when the window is scaled.
var count =;
Window.onresize = function () {
count++;
Console.log (count);
}
In Chrome browser, the size of the Telescopic browser window is printed as follows
This is obviously not what we want, then if we change to Ajax request, then zoom in a window will trigger a number of AJAX requests, the following we try to use the function throttle operation to try; Of course, add a settimeout () timer on the good,
The first method of encapsulation
var count =;
function Ocount () {
count++;
Console.log (count);
}
Window.onresize = function () {
delayfun (ocount)
};
function Delayfun (method, Thisarg) {
cleartimeout (method.props);
Method.props = settimeout (function () {
method.call (thisarg)
},)
}
The second method of encapsulation
Construct a closure that uses closures to form a private scope for storing timer timers, which are introduced in the form of parameters.
var count =;
function Ocount () {
count++;
Console.log (count);
}
var funs= delayfun (Ocount,);
Window.onresize = function () {
funs ()
};
function Delayfun (func, wait) {
var timer = null;
return function () {
var context = This,
args = arguments;
Cleartimeout (timer);
Timer = settimeout (function () {
func.apply (context, args);
}, wait)
};
}
Optimized for the second method, performance would be better
This returns a function, which will not be executed if it is invoked without interruption. The function calls it again after it stops calling N milliseconds before it is executed. If there is a pass ' immediate ' parameter, the function is immediately scheduled into the execution queue without delay.
function Delayfun (func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply (context, args);
var callnow = immediate &&!timeout;
Cleartimeout (timeout);
Timeout = settimeout (later, wait);
if (Callnow) func.apply (context, args);
}
;}; Usage
var myefficientfn = Delayfun (function () {
//All heavy Operations
},);
function does not allow callback functions to execute more than once in a specified time. This function is particularly important when assigning a callback function for an event that is frequently triggered.
SetTimeout is so powerful, can we use it extensively in the project?
I personally do not recommend that in our business, basically prohibit the use of settimeout in the business logic, because I see a lot of ways to use are some problems 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.
About JS SetTimeout Clever use of the front-end function throttling, small series to introduce to everyone here, hope to help everyone!