views:

55

answers:

4

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

+3  A: 

The specifications from Microsoft, Sun and Mozilla just say that it will return an integer. So 0 is probably included.

It may be possible (and probable) that some implementations exclude 0 but you shouldn't rely on that. You should go with the !==.

To summarize: Although probably all browser exclude 0 from the IDs returned by setTimeout, you should not write your code with that in mind especially when all your have to do is add an extra =.

Alin Purcaru
+1 Thanks. You did answer my question, though the accepted answer addressed my concern.
aip.cd.aish
+1  A: 

It shouldn't, given this:

handle = window . setTimeout( handler [, timeout [, arguments ] ] )

Let handle be a user-agent-defined integer that is greater than zero that will identify the timeout to be set by this call.

Felix Kling
Aren't those HTML5 specs?
Alin Purcaru
@Alin: I came to this site via https://developer.mozilla.org/en/DOM/window.setTimeout, where it says that it is part of DOM Level 0. So I thought this actually older than HTML5, but maybe I misinterpreting something.
Felix Kling
+1 Thanks for the link. You did answer my question, though the accepted answer addressed my concern.
aip.cd.aish
A: 

Most browsers will return an int starting at 1 and incrementing for each call of setTimeout so in theory it could never be 0.

But keep in mind that this is not really a requirement of the spec, just a convention browsers tend to follow. See the accepted answer here for more details: http://stackoverflow.com/questions/940120/setinterval-settimeout-return-value

brendan
A: 

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

DoXicK
My mistake :) I didn't check, but yes `0 != null` always. I expected them to be equal in Javascript, considering equalities like '' and 0 - but this is not the case.
aip.cd.aish