JavaScript之mj-debounce-throttle插件、封装、防抖、节流、define、global、clearTimeout、setTimeout、self、module、exports


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);
                }
            };
        }
    };
}));

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/125227331