"Source" anti-shake and throttle source analysis

Source: Internet
Author: User

Objective

Anti-shake, throttling is mainly used for frequent event triggering, such as mouse movement, changing window size. Lodash and other function libraries have corresponding APIs, _.debounce _.throttle .

Core technology: Closures.

Difference:

    • Anti-shake, continuous trigger, first and last trigger valid
    • Throttling, triggering only once (first time) over a period of time

This article is to prevent the chattering function as an example, detailed description.

Realize

Principle, the timer stores the state.

function debounce(fn, delay) {    return function() {        console.log(fn.timer, count2);        let _this = this;        let _args = arguments;        fn.timer !== undefined && clearTimeout(fn.timer);        fn.timer = setTimeout(function() {            fn.apply(_this, _args);        }, delay);    }}// 替换debounce(oldFunction, delay)();

Improved, can be called in multiple places

/** * 防抖函数*/function debounce(fn, delay) {    let timer;    return function () {        let _this = this;        let _args = arguments;        console.log(timer, count2)        timer !== undefined && clearTimeout(timer);        timer = setTimeout(function () {            fn.apply(_this, _args);        }, delay);    }}var newFucntion = debounce(oldFunction, delay);// 替换newFunction();

My test connection, open the console view

Reference

Inspiration-Mint Weekly, with errors, for reference only

Reference Blog

Reference Demo

"Source" anti-shake and throttle source analysis

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.