Can setTimeout ever return 0 as the id?

前端 未结 4 519
心在旅途
心在旅途 2021-01-03 17:48

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         


        
相关标签:
4条回答
  • 2021-01-03 18:32

    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

    0 讨论(0)
  • 2021-01-03 18:44

    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.

    0 讨论(0)
  • 2021-01-03 18:47

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

    0 讨论(0)
  • 2021-01-03 18:48

    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 讨论(0)
提交回复
热议问题