What is the main difference between
and
in JavaScript?
setTimeout(expression, timeout);
runs the code/function once after the timeout.
setInterval(expression, timeout);
runs the code/function repeatedly, with the length of the timeout 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.
setInterval
fires again and again in intervals, while setTimeout
only fires once.
See reference at MDN.
setTimeout()
:
It is a function that execute a JavaScript statement AFTER
x interval.
setTimeout(function () {
something();
}, 1000); // Execute something() 1 second later.
setInterval()
:
It is a function that execute a JavaScript statement EVERY
x interval.
setInterval(function () {
somethingElse();
}, 2000); // Execute somethingElse() every 2 seconds.
The interval unit is in millisecond
for both functions.
setInterval()
setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().
if you want to loop code for animations or clocks Then use setInterval.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout()
setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.
function loopingTimeout(){setTimeout(function(){console.log("Timed out!");loopingTimeout();}, 1000)};
–
Jasisa function loopingInterval(){setInterval(function(){console.log("Soon this will spawn thousands of setIntervals and most likely freeze your browser.");loopingInterval();}, 1000)};
–
Jasisa setInterval
repeats the call, setTimeout
only runs it once.
© 2022 - 2024 — McMap. All rights reserved.
execute_once_after()
andexecute_each()
, also I think avoiding longer (but clear) variable/function names due to camel case is a big mistake in current development literature, as modern IDE do autocomplete efficiently and there is no need to use such ciphered trimmed statement, I personally much prefer snake case to give descriptive functions and variables names, it saves the reader's psychological health ;). – Kingsize