Function throttling in JavaScript

Source: Internet
Author: User

I. Background

In some scenarios, functions may be called frequently, and these functions occupy a large amount of memory or computing, which may cause high performance problems. For example:

Window. onresize event. The window. onresize event is triggered when the browser window size changes. Each time the browser changes 1px, this event is triggered once, and the trigger frequency is very high. If some DOM node-related operations are involved in the window. onresize event, DOM operations are often very memory-consuming, and the browser may crash or even crash.
Mousemove event. If you bind a mousemove event to a div element, the mousemove event function is also frequently triggered when you move the mouse over the div.
Window. onscroll event. The window. onscroll event is triggered when the page is rolled, and every 1px page is triggered, and the trigger frequency is also very high.
Change event. Each time you change the value in the input and textarea elements, the change event is triggered. When the user input is fast, and the change event function may involve DOM operations and other memory-consuming operations, it may cause a choppy problem.
... ...
In fact, we don't need to trigger these event functions so frequently, as long as we can ensure a smooth user experience.

For example, if you drag a browser window to change its size, the window. onresize event function may be triggered 100 times. In fact, we only need 3 or 4 times to achieve a smooth user experience. This requires using the function to throttle and ignore some event requests by time period. This can be achieved through the setTimeout function.

Therefore, the function throttling must reduce the frequency of triggering callback.

II. Principle of function throttling

The principle of function throttling is to use setTimeout to delay the function to be executed for a period of time. If the statement execution is not completed, ignore the next request to call the function.

III. Code implementation of function throttling

/*
* Throttling function
* @ Param {Function} fn the Function to be throttled
* @ Param {Int} the interval at which the delay function is executed. The default value is 500.
*/
Var throttle = function (fn, delay ){
Var _ self = fn, // Save the function reference to be delayed
Timer = null, // timer
FirstTime = true; // whether it is the first call

Return function (){
Var args = arguments,
_ This = this,
Delay = delay | 500;

// If this is the first call, no execution delay is required.
If (firstTime ){
_ Self. apply (_ this, args );
FirstTime = false;
Return;
            }

If (timer ){
Return false;
            }

// Execution is delayed for a period of time
Timer = setTimeout (function (){
// Clear the timer
ClearTimeout (timer );
Timer = null;

_ Self. apply (_ this, args );
}, Delay );
};
}
/* = Client call = */
Window. onresize = throttle (function (){
Console. log ("Window is resizeing .");
},200 );
IV. Summary

Function throttling is suitable for scenarios that require frequent calls but must execute logic within a certain period of time.

The function throttling method can significantly improve the page performance and interactive experience, while the function throttling frequency can be obtained only after debugging in the actual project.

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.