Skip to content

Can setTimeout ever return 0 as the id?

I am writing a check to see if a timeout is active. I was thinking of doing this:

var a = setTimeout(fn, 10);
// ... Other code ... where clearTimeout(a) can be called and set to null
if (a != null)
{
   // do soemthing
}

I was wondering if it would ever be possible that a will be 0. In that case I would use a !== null

Answer

First: 0 isn’t the same as null, (0 == null) would be false in every case’;

if you want to test ‘a’ against something: define ‘a’ first and later assign the settimeout to ‘a’. then check against the type of ‘a’. If its ‘undefined’, the timer hasn’t triggered yet