完整版节流防抖

986 阅读1分钟

防抖函数

防抖函数的作用就是控制函数在一定时间停留后的执行

    function debounce(fn, wait = 200, immediate) {
        if (typeof fn !== 'function') throw "argument[0] must be the function";
        let timeout = null;
        const debounce = function () {
            const context = this, args = arguments;
            clearTimeout(timeout);
            if (immediate && !timeout) fn.apply(context, args);
            timeout = setTimeout(function () {
                if (!immediate) fn.apply(context, args);
                timeout = null;
            }, wait);
        }
        debounce.cancel = function () {
            clearTimeout(timeout);
            timeout  = null;
        }
        return debounce;
    };

节流函数

节流函数的作用就是控制函数单位时间内执行

    function throttle(fn, wait = 1200,immediate) {
        if(typeof fn !== 'function') throw "argument[0] must be the function";
        let last = 0,timeout;
        const throttle=function () {
            const now = Date.now();
            if (last && now < last + wait){
               if(!immediate&&!timeout){//执行第一次函数
                    clearTimeout(timeout);
                    const context=this,args=arguments;
                    timeout = setTimeout(function () {
                        last = now;
                        timeout = null;
                        fn.apply(context, args);
                    }, wait);
                }
                return;
            };
            if(!immediate && timeout) return;
            last = now;
            fn.apply(this, arguments);
        }
        throttle.cancel=function(){
            clearTimeout(timeout);
            timeout = null;
            last=0;
        }
        return throttle;
    };
    function throttle(fn, wait = 1200, immediate) {
        if (typeof fn !== 'function') throw "argument[0] must be the function";
        let last = 0, timeout;
        const throttle = function () {
            const now = Date.now();
            if (last && now < last + wait) {
                if (!immediate) {
                    clearTimeout(timeout);
                    let context = this, args = arguments,
                    remain=last + wait - now;
                    if(remain<0) remain=0;
                    timeout = setTimeout(function () {
                        last = now;
                        timeout = null;
                        fn.apply(context, args);
                    }, remain);//执行最近一次函数
                }
                return;
            }
            if (!immediate && timeout) return;
            last = now;
            fn.apply(this, arguments);
        }
        throttle.cancel = function () {
            clearTimeout(timeout);
            timeout = null;
            last = 0;
        }
        return throttle;
    };