防抖与节流

  • 防抖:事件持续触发,但只有当事件停止触发后n秒才执行函数。
  • 节流:事件持续触发时,每n秒执行一次函数。

防抖

const debounce = function (func, delay, immediate = false) {
    let timer,
        result,
        callNow = true;
    const debounced = function () {
        const context = this;
        const args = arguments;
        if (timer) clearTimeout(timer);
        if (immediate) {
            if(callNow) result = func.apply(context, args);
            callNow = false;
            timer = setTimeout(() => {
                callNow = true; // 过n秒后才能再次触发函数执行。
            }, delay)
        } else {
            timer = setTimeout(() => {
                func.apply(context, args);
            }, delay)
        }
        return result;
    };
    debounced.cancel = function(){
        clearTimeout(timer);
        timer = null;
    }
}

节流

const throttle = function(func, delay) {
    let timer,
        prev = 0;
    return function(){
        const context = this;
        const args = arguments;
        const now = +new Date();
        const remaining = delay - (now - prev);
        if (remaining <= 0) {
            prev = now;
            func.apply(context, args);    
        } else if(!timer) {
            timer = setTimeout(() => {
                prev = +new Date();
                timer = null;
                func.apply(context, args);    
            }, remaining)    
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本篇文章主要介绍防抖和节流的原理,以及它们的区别。 防抖与节流的问题总是会在面试中出现(然而我并没有遇到),如果你...
    黑色瓶子阅读 1,163评论 0 3
  • 本篇课题,或许早已是烂大街的解读文章。不过春招系列面试下来,不少伙伴们还是似懂非懂地栽倒在(~面试官~)深意的笑容...
    以乐之名阅读 1,802评论 0 9
  • 在进行窗口的resize、scroll,输入框内容校验等操作时,如果事件处理函数调用的频率无限制,会加重浏览器的负...
    iqing2012阅读 813评论 0 1
  • 之前实习的时候,我遇到了这么一个需求,搜索框实时发送请求,在做这个功能时我忽略了一个很严重的问题,我把处理请求的函...
    wangmu_mu阅读 456评论 0 1
  • 防抖和节流都是为了解决短时间内大量触发某函数而导致的性能问题,比如触发频率过高导致的响应速度跟不上触发频率,出现延...
    _SweetHeart阅读 404评论 0 1