Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, clearTimeout setInterval and clearInterval.
The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) and clearTimeout(id) function instructs the timer to stop.
SetTimeout and ClearTimeout Demo
var myVar = setTimeout(function(){ alert(“Hello”); }, 3000);
function myStopFunction() {
clearTimeout(myVar);
}
SetInterval and ClearInterval Demo
var myVar = setInterval(function(){ alert(“Hello”); }, 1000);
function myStopFunction() {
clearInterval(myVar);
}
Difference between setTimeout and setInterval
The setTimeout & setInterval are the 2 timers functions of JavaScript. They can be used to create functions that executes 1 time or unlimited times. That is, if you want a function to frontend interview questions execute 1 time then use .setTimeout(), if you want to execute a function unlimited times then use .setInterval().
1. I want to show an alert just one time after 3 seconds.
setTimeout(function(){ alert("Hi"); }, 3000);
2. I want to show an alert unlimited time after every 3 seconds.
setInterval(function(){ alert(“Hi”); }, 3000);
How to Fix setTimeout() problem in a Loop?
function doSetTimeout(i) {
setTimeout(function() { alert(i); }, 100);
}
for (var i = 1; i < 10; ++i) {
doSetTimeout(i);
}