JavaScript setTimeout, order of operations, clearTimeout


Example

setTimeout

  • Executes a function, after waiting a specified number of milliseconds.
  • used to delay the execution of a function.

Syntax : setTimeout(function, milliseconds) or window.setTimeout(function, milliseconds)

Example : This example outputs "hello" to the console after 1 second. The second parameter is in milliseconds, so 1000 = 1 sec, 250 = 0.25 sec, etc.

setTimeout(function() {
    console.log('hello');
}, 1000);

Problems with setTimeout

if you're using the setTimeout method in a for loop :

for (i = 0; i < 3; ++i) {
  setTimeout(function(){
    console.log(i);
  }, 500);
}

This will output the value 3 three times, which is not correct.

Workaround of this problem :

for (i = 0; i < 3; ++i) {
  setTimeout(function(j){
    console.log(i);
  }(i), 1000);
}

It will output the value 0,1,2. Here, we’re passing the i into the function as a parameter(j).

Order of operations

Additionally though, due to the fact that Javascript is single threaded and uses a global event loop, setTimeout can be used to add an item to the end of the execution queue by calling setTimeout with zero delay. For example:

setTimeout(function() {
    console.log('world');
}, 0);

console.log('hello');

Will actually output:

hello
world

Also, zero milliseconds here does not mean the function inside the setTimeout will execute immediately. It will take slightly more than that depending upon the items to be executed remaining in the execution queue. This one is just pushed to the end of the queue.

Cancelling a timeout

clearTimeout() : stops the execution of the function specified in setTimeout()

Syntax : clearTimeout(timeoutVariable) or window.clearTimeout(timeoutVariable)

Example :

var timeout = setTimeout(function() {
    console.log('hello');
}, 1000);

clearTimeout(timeout); // The timeout will no longer be executed