JavaScript Intervals and Timeouts

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • 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 not specified, it defaults to 0 milliseconds. However, the actual delay will be longer than that; for example, the HTML5 spec specifies a minimum delay of 4 milliseconds.

Even when setTimeout is called with a delay of zero, the function that is called by setTimeout will be executed asynchronously.

Note that many operations like DOM manipulation are not necessarily completed even if you've made the operation and moved on to the next code sentence, so you shouldn't assume they will run synchronously.

Using setTimeout(someFunc, 0) enqueues the execution of the someFunc function at the end of the current JavaScript engine's call stack, so the function will be called after those operations completed.

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.



Got any JavaScript Question?