'setInterval' vs 'setTimeout' [duplicate]
Asked Answered
G

5

336

What is the main difference between

setInterval

and

setTimeout

in JavaScript?

Greff answered 23/4, 2010 at 6:38 Comment(2)
from the summary of each of your provided links (hint hint - see words in bold) : setInterval - "Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function." ; setTimeout - "Calls a function or executes a code snippet after specified delay"Transcaucasia
They should have renamed these functions to something more relevant, like execute_once_after() and execute_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
A
552

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.
Anacoluthon answered 23/4, 2010 at 6:42 Comment(5)
I have a div I want to display once the page loads and fade away after X seconds. Would using setTimeout with a function which changes the style to display none accomplish this?Omniumgatherum
I've heard that setTimeout is better for animations? Any validity to this?Brina
if the page refresh then set interval is also reset or not?Marniemaro
@lunixbochs, can you say, does setInterval or setTimeout also refreshed when page refreshed?Castilian
JavaScript execution is completely reset when a page is closed or reloaded. This applies to setInterval and setTimeout as well.Anacoluthon
A
89

setInterval fires again and again in intervals, while setTimeout only fires once.

See reference at MDN.

Ayn answered 23/4, 2010 at 6:40 Comment(0)
P
83

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.

Puleo answered 23/4, 2010 at 6:44 Comment(0)
C
38

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.

Convulse answered 14/8, 2013 at 5:32 Comment(4)
This is a more thorough explanation than the others. The use case for setInterval for looping animations is very helpful. To improve this answer more, would you provide a worked example to explain what you mean by "It should not be nested into its callback function by the script author to make it loop, since it loops by default"? Perhaps an example of what not to do followed by an example of what should be done when the author expects to use loops?Ferdinand
You might want to nest a setTimeout to make it loop. function loopingTimeout(){setTimeout(function(){console.log("Timed out!");loopingTimeout();}, 1000)};Jasisa
But it's probably not a good idea to to the same thing with setInterval, since setInterval will already loop by default. function loopingInterval(){setInterval(function(){console.log("Soon this will spawn thousands of setIntervals and most likely freeze your browser.");loopingInterval();}, 1000)};Jasisa
This should be the answer especially with the good details!Bouillabaisse
E
33

setInterval repeats the call, setTimeout only runs it once.

Edgington answered 23/4, 2010 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.