setTimeout and Cleartimeout Examples in javascript with examples

Sometimes, you may need to execute code after a certain waiting period.

JavaScript provides setTimeout and clearTimeout methods for executing and canceling timers for a one-time event.

setTimeout is used to execute code after a specified time in milliseconds has elapsed. It runs only once.

Here’s the syntax:

setTimeout(callbackFunction, timeInMilliseconds);
setTimeout("callbackFunction()", timeInMilliseconds);

callbackFunction is the function that will execute after the given time.

timeInMilliseconds is the time in milliseconds. Note that one second equals 1000 milliseconds.

The returned value is a timer ID that represents the timer, which can be passed to clearTimeout() to cancel the timer.

Internet Explorer 11 accepts a third parameter. Here’s an example of executing a callback function after 3 seconds:

console.log("start");
timeout = setTimeout(callbackfunction, 3000);

function callbackfunction() {
  console.log("callbackfunction");
}
console.log("end");

Output:

start
end
callbackfunction

clearTimeout Method in JavaScript

The clearTimeout() method is used to stop the execution of a function after a specified time in milliseconds.

clearTimeout(timeobject);

Here is an example

console.log("start");
timeout = setTimeout(callbackfunction, 3000);

function callbackfunction() {
  console.log("callbackfunction");
}
clearTimeout(timeout);
console.log("end");

Output:

start
end

How to Pass Parameters to the Function in setTimeout

You can pass function parameters only in IE11; other browsers do not support this feature.

console.log("start");
timeout = setTimeout(callbackfunction, 3000, "John");

function callbackfunction(str) {
  console.log("callbackfunction: ", str);
}
clearTimeout(timeout);
console.log("end");

Output:

start
end
callbackfunction John

Similarly, you can call the function with arguments inside the callback:

setTimeout(function(){
  myfunction(str,str1,str3,... strN);
}, 1000);

function myfunction(str,str1,str3,... strN) {
console.log("callbackfunction: ",str)

}

Notes:

Timeout objects are automatically canceled after the browser is closed or the page is exited.