setTimeout
returns a number, a timeoutId, which is used by clearTimeout
to identify and remove it.
However, what value do I use if I want to set the timeout conditionally? Is 0 a safe ID to use?
It’s used in a React context where clearing the timeout is generally considered good practice.
useEffect(() => { const timeout = success ? setTimeout(() => foo(), 300) : defaultVal; return () => clearTimeout(timeout); }, [success]);
Or is it perhaps better to wrap the entire thing in one big condition and avoid the default value altogether?
useEffect(() => { if (success) const timeout = setTimeout(() => foo(), 300); return () => clearTimeout(timeout); } }, [success]);
Advertisement
Answer
Yes, 0 is a safe value to use because it will never be returned by setTimeout
:
… let id be an implementation-defined integer that is greater than zero …
And it’s not an error to pass 0 to clearTimeout
:
The
clearTimeout(id)
[…] method steps are to remove this’s map of active timers[id].…
To remove an entry from an ordered map is to remove all entries from the map that match a given condition, or do nothing if none do.
But even though it’s safe and supported, I normally use null
for this case. That means I need to check for a non-null
value before calling clearTimeout
, but it makes the intent of the code clearer.