JavaScript Timers
JavaScript timers let you call a function after a delay or at regular intervals.
The browser manages the waiting period while JavaScript continues running other code.
When the period has finished, JavaScript calls the function as soon as possible.
JavaScript Timer Functions
JavaScript provides two timer functions.
| Function | Description |
|---|---|
setTimeout() |
Runs a function once after a delay. |
setInterval() |
Runs a function repeatedly. |
The setTimeout() Function
The setTimeout() function schedules a function to run once after a specified delay.
setTimeout(function, milliseconds);
The first argument is the function to run.
The second argument is the delay in milliseconds.
Example
setTimeout(myFunction, 3000);
function myFunction() {
myDisplayer("I Love You !");
}
In the example above, myFunction is passed to
setTimeout() as an argument.
3000 is the number of milliseconds before
myFunction will be called.
When you pass a function as an argument, remember not to use parenthesis.
Right: setTimeout(myFunction, 3000);
Wrong: setTimeout(myFunction(), 3000);
Instead of passing a function name as an argument to another function, you can always pass the whole function instead:
Timers Use Callback Functions
The function passed to setTimeout() is called a callback function.
A callback is simply a function that is passed to another function.
The callback itself is not asynchronous.
In the examples above, the browser timer causes the callback to run later.
Timers Do Not Stop JavaScript
Starting a timer does not pause JavaScript.
JavaScript immediately continues with the next statement.
Example
myDisplayer("Start");
setTimeout(function () {myDisplayer("Timer")}, 2000);
myDisplayer("End");
Output:
End
Timer
The Delay Is a Minimum
The delay specifies the earliest time the callback can run.
If JavaScript is busy, the callback must wait.
Example
setTimeout(function () {myDisplayer("Timer")}, 1000);
let i = 4e9;
while (--i > 0);
The callback runs after the while loop finishes.
Cancel a Timer
The setTimeout() function returns a timer identifier.
The identifier can be passed to clearTimeout().
Example
const timer = setTimeout(myFunction, 5000);
clearTimeout(timer);
The setInterval() Function
The setInterval() function repeatedly runs a callback.
setInterval(function, milliseconds);
Example
Display the current time every second.
setInterval(showTime, 1000);
function showTime() {
myDisplayer(new Date().toLocaleTimeString());
}
In the example above, showTime is passed to setInterval() as an argument.
1000 is the number of milliseconds between every time
showTime will be called.
Stop an Interval
The clearInterval() function stops an interval.
Example
const timer = setInterval(showTime, 1000);
clearInterval(timer);
Repeated setTimeout()
Some applications repeatedly call setTimeout() instead of using setInterval().
This guarantees that one execution finishes before the next delay begins.
Example
function repeat() {
myDisplayer("Hello");
setTimeout(repeat, 1000);
}
repeat();
Common Timer Mistakes
Wrong:
setTimeout(myFunction(),1000);
Correct:
setTimeout(myFunction,1000);
Wrong:
setTimeout("myFunction",1000);
Wrong expectation
Example
setTimeout(...,0)
Does not mean:
Run immediately.
It means:
Run as soon as JavaScript is ready.
Common Beginner Confusion
Example
myDisplayer("A");
setTimeout(function() {
myDisplayer("B");
}, 1000);
myDisplayer("C");
Try it Yourself »
The output from the above example is A C B.
Example
let result;
setTimeout(function() {
result = 5;
}, 1000);
// What is result here?
Try it Yourself »
Result is undefined because the async code has not finished yet.
Beginners expect async results immediately.
How do Timers Work?
Timers are managed by the browser.
When a timer expires, its callback waits until JavaScript is ready to run it.
For a complete explanation, see the JavaScript Event Loop chapter.
Summary
setTimeout()runs a function once after a delay.setInterval()runs a function repeatedly.- The browser manages the waiting period.
- The callback runs when JavaScript is ready.
- The specified delay is a minimum delay.
- Use
clearTimeout()andclearInterval()to stop timers.