8

The HTML5 specifications states that setTimeout can be run without the additional "timeout" argument which is supposed to say after how many milliseconds will the function "handler" be scheduled.

handle = window . setTimeout( handler [, timeout [, arguments ] ] )
   Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

However, I failed to find anywhere which explains what happens when no "timeout" time period is set.

An example usage is, the animation implementation int the Raphael library.

animationElements[length] && win.setTimeout(animation);
Elazar Leibovich
  • 32,750
  • 33
  • 122
  • 169
  • All current major browsers are able to accept a single argument, so to avoid any confusion it's worth pointing out that a browser does not have to be HTML5 compliant to support this. – Andy E Apr 27 '10 at 18:09
  • 2
    This is a splendid way of doing deferred procedure calls in JS - "do X later/not-right-now". If you're inside an event handler, it may be a bad time to call some function because of state/re-entrancy issues. Note that you cannot guarantee the actual execution time, but it's "soon". – JBRWilkinson Apr 27 '10 at 18:28
  • @Andy Mozilla MDC states the millisecond as a mandatory parameter. – Elazar Leibovich Apr 27 '10 at 18:34
  • @JBRWilkinson: Indeed, and it's also a great way to delay execution with the possibility of cancelling it if a particular event fires. I've used this technique numerous times and it's really useful. – Andy E Apr 27 '10 at 19:02
  • Related: [Why is setTimeout(fn, 0) sometimes useful?](/q/779379/4642212), [NodeJS - setTimeout(fn,0) vs setImmediate(fn)](/q/24117267/4642212). – Sebastian Simon Sep 25 '21 at 16:56

1 Answers1

17

See http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#get-the-timeout

  1. Let timeout be the second argument to the method, or zero if the argument was omitted.
Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • 7
    Beat me to it :-) +1. I was going to add to my own answer (but may as well add it here) that just because the timeout argument is 0 doesn't necessarily mean it will run instantly, it will still be queued to run when the thread becomes idle, e.g. after all current code execution is finished. – Andy E Apr 27 '10 at 17:53
  • 1
    FYI, the above referenced document has been changed so that it now just reads: "Let timeout be the second argument to the method." However, the Mozilla documentation does document this behavior here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout – minorgod Sep 22 '15 at 18:02