今天在看大神节流的文章,但是博客例子中的一段代码无法理解
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)
}
}
}
在第3秒时,是只执行了第1秒设置的setTimeout函数吗(此时第1秒设置的函数时间到了)?没有执行整个节流函数?
原文:https://github.com/mqyqingfen...
https://juejin.cn/post/684490...
你大约是没理解throttle怎么使用的,点拨一下就清楚了:
throttle是一个高阶函数,接受func作为参数,并返回一个包裹了func的函数(下文称为wrap)。就像原文的用法一样:
后续你执行函数时,是在执行container.onmousemove