setTimeout and setInterval - scheduling

what is scheduling? When we decide to do something at some specific time or after certain amount time. In javascript/node.js we can call function and do some task after certain amount of time.

There is two of doing this and we will learn of that. These are global function and available without importing anything or adding any library.

  • setTimeout
  • setInterval

setTimeout

This function is used to schedular a function execution after certain time. i.e If you want to ask for user email for newsletter but after spending 30 seconds on your website. This is one of the practical use case.

Syntax of setTimeout

setTimeout(callback, waitingTime);

You can see that setTimeout takes two argument.

  • waitingTime : How much time to wait
  • callback : What function to call/execute after waitingTime.

The waiting time is in the milliseconds (1 second == 1000 milliseconds)

You can use any of the either way both are common.


You can define the function and time and assign or pass the value as arguments to the function.

demo-1.js
function printHello() {
  console.log("I waited 10,000 ms");
}
var waiting = 10000; // It's 10 seconds

setTimeout(printHello, waiting);
  • You should use this when you want to re-use the function or time somewhere else also.
  • This is more readable.

If you don’t want declare and pass as arguments then you can directly pass the method and time.

demo-2.js
setTimeout(function () {
  console.log("I will be called after 5 seconds");
}, 5000);
  • This is less readable and become mess when you have giant function.
  • You should use when you don’t want to re-use the time and function anywhere else in the program.

setInterval