开发者

Can setTimeout ever return 0 as the id?

开发者 https://www.devze.com 2023-01-20 07:23 出处:网络
I am writing a check to see if a timeout is active. I was thinking of doing this: var a = setTimeout(fn, 10);

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


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.


The specifications from Microsoft, Sun and Mozilla just say that it will return an integer. So 0 may be 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 =.


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


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: setInterval/setTimeout return value

0

精彩评论

暂无评论...
验证码 换一张
取 消