In JavaScript all instructions are executed one by one. If you want to execute a piece of code at a later time or execute it at a specific interval you need to use the built in functions setTimeout and setInterval.
setTimeout method
The method is used for delaying code execution. It receives 2 parameters the first one is an expression and the second one is the delay time.
setTimeout(function() {
console.log(‘Hello I am inside the setTimeout’);
}, 1000);The code above we’ll be executed after one second.
clearTimeout method
This method is used to clear a timer that was set with setTimeout. It receives one parameter the id returned by setTimeout when setting the timer.
Let’s see an example:
var timerId = setTimeout(function() {
console.log(‘print this after a second’);
}, 1000);
// to clear the timer we call the clearTimeout function
clearTimeout(timerId);In the above example the setTimeout is not executed anymore, because the clear timeout method is called and the timer is cleared.
setInterval method
The method is used when you want to execute a piece of code at a specific interval. Like the setTimeout method it receive 2 parameters The first one is the callback that will be executed and the second parameter is the interval time in milliseconds.
let counter = 0;
setInterval(function(){
counter +=1;
console.log(‘seconds’, counter);
}, 1000);The code will increment and print the counter variable every second.
clearInterval method
The method is used to clear a timer set by setInterval. Like the clearInterval method it also receives the id of the timer that was created by setInterval when setting the timer.
const element = document.getElementById('box');
const timerId = setInterval(function() {
element.style.width += 10
}, 1000)
setTimeout(function() {
clearInterval(timerId)
}. 6000)In the above example the width of the element will be increased by 10 every second. after 6 seconds the setInterval will be cleared.