Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

JS Tutorial

JS Home JS Introduction JS Where To JS Output JS Syntax JS Operators JS If Conditions JS Loops JS Strings JS Numbers JS Functions JS Timers JS Objects JS Scope JS Dates JS Temporal  New JS Arrays JS Sets JS Maps JS Iterations JS Math JS RegExp JS Data Types JS JSON JS Errors JS Debugging JS Style Guide JS Reference JS Projects  New JS Versions JS HTML DOM JS HTML Events JS HTML First

JS Advanced

JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Browser API JS Web API JS Graphics

Old Technologies

JS AJAX JS jQuery

JS Examples

JS Examples

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!");
}

Try it Yourself »

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

Example

setTimeout(function() {
  myDisplayer("Hello!");
}, 3000);

Try it Yourself »


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

Try it Yourself »

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

Try it Yourself »



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);

Try it Yourself »

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";
}

Try it Yourself »


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());
}

Try it Yourself »


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;
}

Try it Yourself »


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;
}

Try it Yourself »


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

Try it Yourself »

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);
}

Try it Yourself »


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);

Try it Yourself »

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;
}

Try it Yourself »

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.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->