Home > Articles > Web Development

  • Print
  • + Share This
Like this article? We recommend

Using setTimeout()

The setTimeout() method is useful for executing a callback function that needs to be executed sometime in the future. The parameters for this method are the callback function to be executed and the time elapsed before it should be executed (in milliseconds). One or more arguments passed to the callback function follow the time parameter.

A simple example of using the setTimeout() method appears below:

setTimeout(function(str1, str2) {
  console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");

Two strings are passed in and then written to the console after a second of waiting before executing the method. You might need to cancel the timeout before the execution of the callback function. The setTimeout() method returns an identifier that can be used with the clearTimeOut() method.

A simple example of using the clearTimeout() method appears below:

var timeOut = setTimeout(function(str1, str2) {
  console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");

clearTimeout(timeOut);

The example above cancels the function call immediately (in real-world scenarios the cancellation would occur based on an event).

  • + Share This
  • 🔖 Save To Your Account