Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 582
Aishwar Avatar asked Oct 15 '10 15:10

Aishwar


People also ask

What happens when setTimeout is 0?

Invoking setTimeout with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.

What is the return value of setTimeout?

Return valueThe returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout() . This value can be passed to clearTimeout() to cancel the timeout.

What is the default value of setTimeout?

First of all, the setTimeout JavaScript method should contain the function that you intend to apply. The second parameter sets a time when the specified function is to be called. However, it is optional, and the default value is 0.


2 Answers

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.

like image 60
Felix Kling Avatar answered Sep 30 '22 02:09

Felix Kling


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 =.

like image 37
Alin Purcaru Avatar answered Sep 30 '22 03:09

Alin Purcaru