Javascript prevents frequently-called debounce Functions

Source: Internet
Author: User
The javascriptdebounce function is essential for executing event-driven tasks to improve performance. If you do not use the frequency reduction function when using scroll, resize, key, and other events to trigger a task, you can also make a major mistake. The following debounce function can make your code more efficient:

// Return a function, that, as long as it continues to be invoked, will not // be triggered. the function will be called after it stops being called for // N milliseconds. if 'immediate' is passed, trigger the function on the // leading edge, instead of the trailing. function debounce (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) ;};}; // Usagevar myEfficientFn = debounce (function () {// All the taxing stuff you do}, 250); window. addEventListener ('resize', myEfficientFn );

debounceA function allows only the provided callback function to be executed once within a given interval, reducing the execution frequency. This restriction is especially important when a high-frequency event is triggered.

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.