This website collects cookies to deliver better user experience
Guide to setTimeout and setInterval in Javascript
Guide to setTimeout and setInterval in Javascript
The global object in Javascript provides two in-built methods setTimeout and setInterval to trigger a block of code at a scheduled time.
setInterval
setInterval method accepts two arguments. A callback function and delay in milliseconds. The function passed is called at specified intervals. setInterval will continue calling the passed function until we use another in-built method clearInterval or until the window is closed.
In this example, the increment function passed as callback, will be called after every one second.
let i =0;functionincrement(){ i++;console.log(i);}setInterval(increment,1000);
setTimeout
setTimeout also accepts two arguements like setInterval. The function passed is called once after the specified interval.
After an interval of one second, the increment function passed to setTimeout will be called.
let i =0;functionincrement(){ i++;console.log(i);}setTimeout(increment,1000);
clearInterval and clearTimeout
The setInterval and setTimeout functions returns a number which is used to identify that particular function. Calling clearInterval and clearTimeout by passing the corresponding id will stop executing it.
In the example shown below, clearInterval will be executed after 3 seconds, thus terminating the setInterval call.
let i =0;functionincrement(){ i++;console.log(i);}const incrementTimer =setInterval(increment,1000);setInterval(()=>{clearInterval(incrementTimer);},3000)