我试图通过 clearTimeout()
销毁前一个计时器来弄清楚为什么我的简单节流函数无法正常工作。它只是行不通,只有 null
赋值才能让我摆脱这个陷阱......
知道为什么吗?谢谢
代码:
const throttler = ({ event, callback, delay, target }) => {
let timerID = null
const eventSubscribeTarget = target || window
const resizeThrottler = () => {
if (timerID) return
timerID = setTimeout(() => {
callback()
timerID = null // <= only by null assigment it's gonna gone...
// clearTimeout(timerID) doesn't work here
}, delay)
}
eventSubscribeTarget.addEventListener(event, resizeThrottler, false)
}
最佳答案
首先,使用timerID
调用clearTimeout
,然后将timerID
设置为null
。
您当前正在做的是将timerID
设置为null
;从而丢失timerID
值。该代码本质上是在执行 clearTimeout(null)
而不是 clearTimeout(20)//假设timerID = 20
。
此外,仅将 timerID
设置为 null
不会取消超时事件:它仍然会运行。因此,为了避免像您这样重复调用 setTimeout
函数的程序中出现内存泄漏和不可预测的行为,请使用您的 timerID
clearTimeout
> 是必须的。如果需要,您可以在此之后将 timerID
设置为 null
。
关于javascript - 计时器只能通过空赋值而不是通过clearTimeout()来销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55489959/