setTimeout and setInterval

JavaScript execution in a browser is single-threaded, but we can schedule a timer to call a function at a later time.


The setTimeout() method sets a timer that expires after a set number of milliseconds. When the timer expires, a predetermined function is executed.

setTimeout(func, delay [,arg1, arg2, …]) takes a reference to a function as a first argument, an integer as a second parameter, followed by zero or more optional arguments. When invoked, the method returns an id that can later be used to terminate the timer.

The setTimeout() method creates a timer that expires after the number of milliseconds specified in the second parameter.  When the timer expires, the function whose reference is passed in as the first argument is passed the optional arguments and executed.  You can stop a timer by passing the id returned by setTiimeout() to the clearTimeout() method.

For example, below the timer executes the named function foo after 2 seconds.  When foo is called, the value 10 is passed into it.

function foo(x) {

setTimeout(foo, 2000, 10);

Below we set a timer to execute an unnamed function after 2 seconds.

var foo = function(x) {

var id = setTimeout(foo, 2000, 10);

We can also use lambda expressions in place of the function reference.

var id = setTimeout((x) => console.log(x*2), 2000, 10);

To stop a timer we pass to the clearTimeout() method the id that was returned by setTimeout().



The setInterval() method works like setTimeout(), except it executes repeatedly until the timer is cleared or the page is unloaded.  You can stop an interval timer by passing clearInterval() an id returned by setInterval().

var id = setInterval(foo, 2000, 10);
setInterval(clearInterval, 6000, id);