1、下载安装命令

npm install mj-debounce-throttle
npm install mj-debounce-throttle --save
npm install mj-debounce-throttle --save-dev

下载安装后,包文件夹的.md文件有使用说明。


2、源码

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
            (global = global || self, global.debounceThrottle = factory());
}(this, function () {
    'use strict';

    return {
        debounce: (fn, delay = 1000) => {
            let timer = null;

            return function () {
                let context = this,
                    args = arguments;

                if (timer) clearTimeout(timer);

                timer = setTimeout(function () {
                    fn.apply(context, args);
                }, delay);
            };
        },
        throttle: (fn, wait = 1500) => {
            let inThrottle,
                lastFn;

            return function () {
                let context = this,
                    args = arguments;

                if (!inThrottle) {
                    fn.apply(context, args);
                    inThrottle = true;
                } else {
                    clearTimeout(lastFn);

                    lastFn = setTimeout(function () {
                        inThrottle = false;
                    }, wait);
                }
            };
        }
    };
}));
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐