Intervals and timeouts
suggest changeSyntax
- timeoutID = setTimeout(function() {}, milliseconds)
- intervalID = setInterval(function() {}, milliseconds)
- timeoutID = setTimeout(function() {}, milliseconds, parameter, parameter, …)
- intervalID = setInterval(function() {}, milliseconds, parameter, parameter, …)
- clearTimeout(timeoutID)
- clearInterval(intervalID)
Remarks
If the delay is omitted, it defaults to 0. The callback still runs on a later timer task, after the current task and after queued microtasks. Browsers clamp nested timers and timers in background tabs, so a requested 0 can become several milliseconds, or about a second in a background tab. The old “minimum of 4 milliseconds” rule is not a blanket minimum for the first timer.
DOM changes made just before setTimeout(someFunc, 0) are not a reason to treat someFunc as synchronous. It runs on a later turn.
It is possible to pass a string containing JavaScript code (setTimeout("some..code", 1000)) in place of the function (setTimeout(function(){some..code}, 1000)). If the code is placed in a string, it will be later parsed using eval(). String-style timeouts are not recommended for performance, clarity and sometimes security reasons, but you may see older code which uses this style. Passing functions has been supported since Netscape Navigator 4.0 and Internet Explorer 5.0.
Scheduling and cancelling a timeout