JavaScript Timers
Run a Function After a Delay
JavaScript timers let you run a function after a delay or repeatedly at fixed intervals.
The two main timer functions are setTimeout() and setInterval().
| Function | Description |
|---|---|
| setTimeout() | Runs a function once after a delay. |
| setInterval() | Runs a function repeatedly. |
| clearTimeout() | Cancels a timeout. |
| clearInterval() | Stops an interval. |
The setTimeout() Function
The setTimeout() function schedules a function to run once after a delay.
Syntax
setTimeout(function, milliseconds);
The first argument is the function to run.
The second argument is the delay in milliseconds.
One second is 1000 milliseconds.
Example
Display a message after three seconds:
// Call a Timeout
setTimeout(myFunction, 3000);
// The callback function
function myFunction() {
myDisplayer("Hello!");
}
Note
When a function name is passed to a function, it is called a callback function.
Passing a Function
Pass only the function name to setTimeout().
Correct:
setTimeout(myFunction, 3000);
Incorrect:
setTimeout(myFunction(), 3000);
The incorrect example calls myFunction() immediately.
Its return value is then passed to setTimeout().
Note
The setTimeout() function times the callback function to run later.
Using an Anonymous Function
You can pass an anonymous function to setTimeout().
Timers Do Not Pause JavaScript
Calling setTimeout() does not pause JavaScript.
JavaScript immediately continues with the next statement.
Example
myDisplayer("Start");
setTimeout(function() {myDisplayer("Timer")}, 3000);
myDisplayer("End");
The output is:
Start
End
Timer
Note
Timer functions schedule the callback to run later.
setTimeout() do not stop JavaScript from running other code.
A Zero Delay
A delay of zero milliseconds does not mean that the callback function will run immediately.
It means that the callback will run as soon as the current JavaScript task has finished.
Example
myDisplayer("Start");
setTimeout(function() {myDisplayer("Timer")}, 0);
myDisplayer("End");
The output is:
Start
End
Timer
The Delay Is a Minimum
The specified delay is the earliest time the callback can run.
The callback may run later if JavaScript is busy.
Example
setTimeout(function() {
myDisplayer("Timer finished");
}, 1000);
let i = 4e9;
while (--i > 0);
The timer delay is one second.
However, the callback cannot run until the loop has finished.
Timers do not interrupt running JavaScript.
A long-running function can delay timer callbacks and make the page unresponsive.
Canceling a Timeout
The setTimeout() function returns a timer identifier.
Pass the identifier to clearTimeout() to cancel the timer.
Syntax
clearTimeout(timerId);
Example
<button onclick="startTimer()">Start Timer</button>
<button onclick="stopTimer()">Stop Timer</button>
<p id="demo"></p>
let timer;
function startTimer() {
timer = setTimeout(function() {
document.getElementById("demo").innerHTML = "Finished";
}, 5000);
}
function stopTimer() {
clearTimeout(timer);
document.getElementById("demo").innerHTML = "Timer stopped";
}
The setInterval() Function
The setInterval() function runs a callback function repeatedly.
Syntax
setInterval(function, milliseconds);
The callback function is called repeatedly with (at least) the specified delay in between.
Example
Display the current time every second:
setInterval(showTime, 1000);
function showTime() {
const date = new Date();
myDisplayer(date.toLocaleTimeString());
}
Canceling an Interval
The setInterval() function returns an interval identifier.
Pass the identifier to clearInterval() to stop the interval.
Syntax
clearInterval(intervalId);
Example
<button onclick="startClock()">Start Clock</button>
<button onclick="stopClock()">Stop Clock</button>
<p id="demo"></p>
let timer;
function startClock() {
if (!timer) {
timer = setInterval(showTime, 1000);
}
}
function showTime() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function stopClock() {
clearInterval(timer);
timer = undefined;
}
Timeout or Interval?
| Use | Function |
|---|---|
| Run a function once after a delay | setTimeout() |
| Run a function repeatedly | setInterval() |
| Cancel a delayed function | clearTimeout() |
| Stop a repeating function | clearInterval() |
Passing Arguments
Arguments passed to setTimeout() or setInterval() are passed to the callback function.
Example
setTimeout(showMessage, 2000, "Hello", "John");
function showMessage(greeting, name) {
document.getElementById("demo").innerHTML = greeting + " " + name;
}
Repeated setTimeout()
You can create a repeating timer by calling setTimeout() again after each task finishes.
Example
function repeat() {
myDisplayer("Hello");
setTimeout(repeat, 1000);
}
repeat();
With repeated setTimeout(), the next delay begins after the current callback has finished.
With setInterval(), the interval continues to schedule callbacks at regular intervals.
Repeated setTimeout() is useful when one task must finish before the next delay begins.
A Countdown Example
Example
<button onclick="startCountdown()">Start Countdown</button>
<p id="demo"></p>
let timer;
function startCountdown() {
clearInterval(timer);
let count = 10;
myDisplayer(count);
timer = setInterval(function() {
count--;
myDisplayer(count);
if (count === 0) {
clearInterval(timer);
myDisplayer("Finished!");
}
}, 1000);
}
Avoid Strings as Timer Code
Timer functions can accept strings, but strings should not be used as JavaScript code.
Not Recommended
setTimeout("myFunction()", 1000);
Recommended
setTimeout(myFunction, 1000);
Passing a function is safer, clearer, and easier to debug.
Timers Run on the Main Thread
The browser manages the waiting period outside the current JavaScript task.
However, the timer callback still runs on the main JavaScript thread.
A long-running timer callback can therefore freeze the page.
Example
setTimeout(function() {
let i = 4e9;
while (--i > 0);
document.getElementById("demo").innerHTML = "Finished";
}, 1000);
The timer delays when the callback starts.
It does not prevent the callback from blocking the page after it starts.
Common Timer Mistakes
Calling the Function Immediately
setTimeout(myFunction(), 1000);
Remove the parentheses when passing the function:
setTimeout(myFunction, 1000);
Forgetting the Timer Identifier
Save the returned identifier if the timer must be canceled later.
const timer = setTimeout(myFunction, 1000);
clearTimeout(timer);
Starting Multiple Intervals
Starting an interval more than once creates multiple repeating timers.
if (!timer) {
timer = setInterval(myFunction, 1000);
}
Expecting Exact Timing
Timer delays are not exact schedules.
Callbacks run only when JavaScript is ready.
Forgetting to Stop an Interval
An interval continues until it is stopped or the page is closed.
clearInterval(timer);
A Slide Show Example
Timers can be used to change images automatically.
This example displays a new image every three seconds.
Example
<img id="slide" src="img_nature.jpg" style="width:100%;max-width:600px">
<button onclick="startSlides()">Start</button>
<button onclick="stopSlides()">Stop</button>
const images = [
"img_nature.jpg",
"img_snowtops.jpg",
"img_mountains.jpg"
];
let index = 0;
let timer;
function showNextSlide() {
index = (index + 1) % images.length;
document.getElementById("slide").src = images[index];
}
function startSlides() {
if (!timer) {
timer = setInterval(showNextSlide, 3000);
}
}
function stopSlides() {
clearInterval(timer);
timer = undefined;
}
The remainder operator % returns the index to zero after the last image.
The test in startSlides() prevents several intervals from running at the same time.
Timers and Asynchronous JavaScript
Timers are browser APIs that schedule callback functions to run later.
They are often used as simple examples of asynchronous JavaScript.
The callback itself is not asynchronous.
The browser timer only causes the callback to be scheduled for later execution.
Learn More:
Asynchronous programming includes:
- Callbacks
- Promises
- async / await
- Event Loop
- Web Workers
To learn how timers fit into asynchronous programming,: