JavaScript Timers
JavaScript timers let you run a function after a delay or repeatedly at fixed intervals.
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
Example Code
javascriptsetTimeout(function, milliseconds);The first argument is the function to run.
The second argument is the delay in milliseconds.
One second is 1000 milliseconds.
Example
Example Code
javascript// Call a Timeout
setTimeout(myFunction, 3000);
// The callback function
function myFunction() {
myDisplayer("Hello!");
}Passing a Function
Pass only the function name to setTimeout().
Correct:
Example Code
javascriptsetTimeout(myFunction, 3000);The incorrect example calls myFunction() immediately.
Its return value is then passed to setTimeout().
Using an Anonymous Function
You can pass an anonymous function to setTimeout().
Example
Example Code
javascriptsetTimeout(function() {
myDisplayer("Hello!");
}, 3000);Timers Do Not Pause JavaScript
Calling setTimeout() does not pause JavaScript.
JavaScript immediately continues with the next statement.
Example
Example Code
javascriptmyDisplayer("Start");
setTimeout(function() {myDisplayer("Timer")}, 3000);
myDisplayer("End");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
Example Code
javascriptmyDisplayer("Start");
setTimeout(function() {myDisplayer("Timer")}, 0);
myDisplayer("End");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
Example Code
javascriptsetTimeout(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
Example Code
javascriptclearTimeout(timerId);Example
Example Code
html**Start Timer
Stop TimerThe setInterval() Function
The setInterval() function runs a callback function repeatedly.
Syntax
Example Code
javascriptsetInterval(function, milliseconds);The callback function is called repeatedly with (at least) the specified delay in between.
Example
Example Code
javascriptsetInterval(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
Example Code
javascriptclearInterval(intervalId);Example
Example Code
html**Start Clock
Stop ClockTimeout 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
Example Code
javascriptsetTimeout(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
Example Code
javascriptfunction 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.
A Countdown Example
Example
Example Code
htmlStart CountdownAvoid 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
Example Code
javascriptsetTimeout(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
Example Code
htmlStart
StopThe remainder operator % returns the index to zero after the last image.
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.
Interactive Code Examples
Syntax
javascriptsetTimeout(function, milliseconds);JS Example 2
javascript// Call a Timeout
setTimeout(myFunction, 3000);
// The callback function
function myFunction() {
myDisplayer("Hello!");
}Correct:
javascriptsetTimeout(myFunction, 3000);JS Example 4
javascriptsetTimeout(function() {
myDisplayer("Hello!");
}, 3000);JS Example 5
javascriptmyDisplayer("Start");
setTimeout(function() {myDisplayer("Timer")}, 3000);
myDisplayer("End");JS Example 6
javascriptmyDisplayer("Start");
setTimeout(function() {myDisplayer("Timer")}, 0);
myDisplayer("End");