JavaScript function throttling and javascript throttling
Some browser computing and processing are much more expensive than others. For example, DOM operations require more memory and CPU time than non-DOM interactions. Consecutive attempts to perform too many DOM-related operations may cause browser suspension and sometimes even crash. This event is especially likely to occur when the onresize event handler is used in IE. When the browser size is adjusted, this event is triggered continuously. If you try DOM operations in the onresize event handler, high-frequency changes may cause the browser to crash.
The basic idea behind function Throttling is that some Code cannot be repeatedly executed without interruption. Call the function for the first time, create a timer, and run the code after the specified interval. When this function is called for the second time, it clears the previous timer and sets another one. If the previous timer has been executed, this operation will be meaningless. However, if the previous timer has not been executed, replace it with a new one. The purpose is to execute the function only after the function execution request is stopped for a period of time.
Copy codeThe Code is as follows:
Function throttle (method, context ){
ClearTimeout (method. tId );
Method. tId = setTimeout (function (){
Method. call (context );
},100 );
}
Example:
Assume that there is a <div/> element that must keep its height always equal to the width, which can be encoded as follows:
Copy codeThe Code is as follows:
Function resizeDiv (){
Var div = document. getElementById ("mydiv ");
Div. style. height = div. offsetWidth + "px ";
}
Window. onresize = function (){
Throttle (resizeDiv );
}
Here, the resize function is put into a separate function called resizeDiv, And the onresize event handler calls throttle () and passes in the resizeDiv function instead of directly calling resizeDiv (). In most cases, the user does not feel the change, although the computation saved on the browser may be very large.