setTimeout and Cleartimeout Examples in javascript with examples

Sometimes, You want to execute code after waiting time.

javascript provides settimeout and clearTimeout methods to execute and cancel timer for one time.

SetTimeout is used to execute the code after configured time in milli seconds waiting or elapsed.

It is executed only once.

Here is a syntax

setTimeout(callbackfunction, timeinmilliseconds);
setTimeout("callbackfunction()", timeinmilliseconds);

callbackfunction is a function that executes after the given time.

timeinmilliseconds is a time in milliseconds. One second is 1000.

Returned value is an timer id that represents the timer, can be passed to clearTimeout() to cancel the timer.

Internet Explorer 11, accepts the third parameter. Here is an example to execute 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 function after 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 the function parameters only in IE11, Other browsers are not supported.

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 canceled automatically after the browser is closed or the page exit.