Home > Web Front-end > JS Tutorial > A brief discussion on JavaScript function throttling_Basic knowledge

A brief discussion on JavaScript function throttling_Basic knowledge

WBOY
Release: 2016-05-16 16:28:09
Original
1495 people have browsed it

Some calculations and processing in the browser are much more expensive than others. For example, DOM operations require more memory and CPU time than non-DOM interactions. Attempting to perform too many DOM-related operations in succession can cause the browser to hang and sometimes even crash. This is especially likely to happen when using the onresize event handler in IE. When the browser is resized, the event is triggered continuously. If you try to perform DOM operations inside the onresize event handler, its high frequency of changes may crash the browser.
The basic idea behind function throttling is that certain code cannot be executed continuously and repeatedly without interruption. The first time the function is called, a timer is created to run code after a specified interval. When this function is called a second time, it clears the previous timer and sets another one. If the previous timer has already been executed, this operation has no meaning. However, if the previous timer has not yet been executed, it is actually replaced with a new timer. The purpose is to execute the function only after the request to execute it has been stopped for some time.
                         

Copy code The code is as follows:

function throttle (method, context){
Cleartimeout (Method.tid);
                    method.tId = setTimeout ( function () {
method.call (context);
, , , , 100);           }

Application examples:
Suppose there is a

element that needs to keep its height equal to its width. It can be encoded as follows:                              

Copy code The 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 functionality is put into a separate function called resizeDiv, and then the onresize event handler calls throttle() and passes in the resizeDiv function instead of calling resizeDiv() directly. In most cases, users will not feel the change, although the calculation saved to the browser may be very large.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template