'Timer goes to be destroyed only via null assignment, instead of clearTimeout()
I'm trying to figure out why my simple throttle func is not working correctly by destroying previous one timer via clearTimeout(). It's just doesn't work, only null assignment gets me up from this pitfall...
Any idea why? Thanks
Code:
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)
}
Solution 1:[1]
The result of the setTimeout() always returns a Number. This number represents the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer.
The clearTimeout function will not reset the number, that is why you have to set your timerID to null when you want to reuse this variable.
https://www.w3schools.com/jsref/met_win_settimeout.asp https://www.w3schools.com/jsref/met_win_cleartimeout.asp
Solution 2:[2]
(clearTimeout - clearInterval mixup aside...)
Here:
if (timerID) return
So setting the timerId value to null will cause the early return here, new timeout won't be set. Exactly what we're after, I presume.
timerID = setTimeout(() => {
callback()
timerID = null // <= only by null assigment it's gonna gone...
// clearTimeout(timerID) doesn't work here
And here, clearTimeout wouldn't do a thing - the timeout has already ticked, the callback has already been called, there's really no longer a timeout to clear. The function is being executed right here, and won't be again. If we want to prevent new timeout being set, then this
timerID = setTimeout(() => {
is the line that can't be executed.
Solution 3:[3]
Firstly, call clearTimeout with timerID, and then set the timerID to null.
What you are currently doing is to set the timerID to null; thereby losing the timerID value. The code is essentially doing clearTimeout(null) instead of clearTimeout(20) // assuming timerID = 20.
Moreover, only setting your timerID to null will not cancel the timeout event: it will still run. So, to avoid memory leaks and unpredictable behaviors in a program which is repeatedly invoking the setTimeout function like yours seems to be doing, clearTimeout with your timerID is a must. You can set your timerID to null after that if you want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mols |
| Solution 2 | |
| Solution 3 | Stephen Isienyi |
