冴羽的throttle节流文章中例子,setTimeout函数与throttle函数的执行顺序。

新手上路,请多包涵

今天在看大神节流的文章,但是博客例子中的一段代码无法理解

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

image.png

在第3秒时,是只执行了第1秒设置的setTimeout函数吗(此时第1秒设置的函数时间到了)?没有执行整个节流函数?
原文:https://github.com/mqyqingfen...
https://juejin.cn/post/684490...

阅读 1.3k
1 个回答

你大约是没理解throttle怎么使用的,点拨一下就清楚了:

  1. throttle是一个高阶函数,接受func作为参数,并返回一个包裹了func的函数(下文称为wrap)。就像原文的用法一样:

    container.onmousemove = throttle(getUserAction, 1000);

    后续你执行函数时,是在执行container.onmousemove

  2. 节流的实现方式是:调用wrap函数时,判断当前是否触发了节流限制,如果没触发,直接执行func,也就是题目中1s的动作;如果触发了,那么开个定时器,等到限制取消再执行(func函数)。所以,3s时,只有定时器对应的函数,也就是func会执行
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题