Problem
What is the main distinction between the two?
setInterval
and
setTimeout
in JavaScript?
Asked by Pranay Rana
Solution #1
setTimeout(expression, timeout) executes the code/function once once the timer has expired.
setInterval(expression, timeout) repeats the code/function with the timeout interval between each repeat.
Example:
var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.
setTimeout(alert, 1000); // Will alert once, after a second.
Answered by lunixbochs
Solution #2
setInterval fires multiple times in a row, but setTimeout only fires once.
MDN has a reference.
Answered by deceze
Solution #3
setTimeout():
It’s a method that runs a JavaScript statement after a certain amount of time has passed.
setTimeout(function () {
something();
}, 1000); // Execute something() 1 second later.
setInterval():
It’s a function that runs a JavaScript command every x seconds.
setInterval(function () {
somethingElse();
}, 2000); // Execute somethingElse() every 2 seconds.
For both functions, the interval unit is millisecond.
Answered by MAS1
Solution #4
setInterval is a time interval-based code execution mechanism that can run a specified script again when the interval is achieved. Because it loops by default, the script author should not nest it within its callback function to make it loop. Unless you call clearInterval, it will continue to fire at the interval ().
Use setInterval if you wish to loop code for animations or clocks.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout is a time-based code execution mechanism that will only run the script once when the interval is reached, unless you tell it to loop it by putting the setTimeout object inside the function it calls to run. Unless you execute clearTimeout, it will keep firing at the interval if it is set to loop ().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
If you want something to happen only once after a certain number of seconds, use setTimeout… because it only runs once when the interval is reached.
Answered by Haris N I
Solution #5
setInterval calls the function many times, but setTimeout simply calls it once.
Answered by Daniel Earwicker
Post is based on https://stackoverflow.com/questions/2696692/setinterval-vs-settimeout