JS TutorialLesson #48

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().

FunctionDescription
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

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
// 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:

Example Code

javascript
Try it Yourself
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().

Example

Example Code

javascript
Try it Yourself
setTimeout(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

javascript
Try it Yourself
myDisplayer("Start");

setTimeout(function() {myDisplayer("Timer")}, 3000);

myDisplayer("End");
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

Example Code

javascript
Try it Yourself
myDisplayer("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

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
clearTimeout(timerId);

Example

Example Code

html
Try it Yourself
**Start Timer

 Stop Timer

The setInterval() Function

The setInterval() function runs a callback function repeatedly.

Syntax

Example Code

javascript
Try it Yourself
setInterval(function, milliseconds);

The callback function is called repeatedly with (at least) the specified delay in between.

Example

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
clearInterval(intervalId);

Example

Example Code

html
Try it Yourself
**Start Clock

 Stop Clock

Timeout or Interval?

UseFunction
Run a function once after a delaysetTimeout()
Run a function repeatedlysetInterval()
Cancel a delayed functionclearTimeout()
Stop a repeating functionclearInterval()

Passing Arguments

Arguments passed to setTimeout() or setInterval() are passed to the callback function.

Example

Example Code

javascript
Try it Yourself
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

Example Code

javascript
Try it Yourself
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

Example Code

html
Try it Yourself
Start Countdown

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

Example Code

javascript
Try it Yourself
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

Example Code

html
Try it Yourself
Start

 Stop

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,: > Read the JavaScript Async Programming Tutorial.

Interactive Code Examples

Syntax

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
setTimeout(function, milliseconds);

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
// Call a Timeout

setTimeout(myFunction, 3000);



// The callback function

function myFunction() {

  myDisplayer("Hello!");

}

Correct:

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
setTimeout(myFunction, 3000);

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
setTimeout(function() {

  myDisplayer("Hello!");

}, 3000);

JS Example 5

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
myDisplayer("Start");



setTimeout(function() {myDisplayer("Timer")}, 3000);



myDisplayer("End");

JS Example 6

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
myDisplayer("Start");



setTimeout(function() {myDisplayer("Timer")}, 0);



myDisplayer("End");