请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

关于节流和防抖的定时器中timer设为null?

// 节流函数
export const throttle = (func, delay = 100) => {
let timer = null;

return function (…args) {
if(timer) {
return
}
timer = setTimeout(() => {
func.apply(this, args)
timer = null
}, delay)
}
}
// 防抖函数
export const debounce = (func, delay = 200) => {
let timer = null

return function (…args) {
timer && clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args)
timer = null
}, delay);
};
};

请问在节流和防抖的settimeout中为什么要设置timer = null,这样设置的话在函数一开始对timer的判断岂不是没有意义,会每次都执行settimeout这个函数

正在回答

1回答

双越 2020-02-06 18:02:24

let timer = null; 和 let timer; 是一样的啊,只不过后者是 unndefined 。

timer 在后面会被赋值的,不会一直是 null 。你可以在 if(timer) 前面加一行 console.log(timer),然后执行看一下。应该就能清晰很多。

1 回复 有任何疑惑可以回复我~
  • 提问者 慕用0863198 #1
    就是说这里if判断的是上一次进行timer = setTimeout(()进行设置的timer,而不是在settimeout里定义的timer,上一次在settimeout里定义的timer是作为下一次的timer = setTimeout(() 。。进行设置的timer,请问可以这样理解嘛
    回复 有任何疑惑可以回复我~ 2020-02-06 18:08:49
  • 双越 回复 提问者 慕用0863198 #2
    对的。
    回复 有任何疑惑可以回复我~ 2020-02-06 19:48:43
  • 提问者 慕用0863198 #3
    非常感谢!
    回复 有任何疑惑可以回复我~ 2020-02-06 20:21:26
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信