🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to JavaScript Notes
Topic #46

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

Col 1 Col 2
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

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

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

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

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

Warning: 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>

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

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>

Timeout or Interval?

Col 1 Col 2
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.

Note: 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>

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>

The remainder operator % returns the index to zero after the last image.

Note: 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.

Note: 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.

Want to go beyond the notes?

Join CodingNow 2.0's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

JS Timers – FAQs

Quick answers about learning JS Timers in JavaScript.

This free note from CodingNow 2.0 explains JS Timers in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on CodingNow 2.0, including JS Timers, is 100% free with no signup required.
With focused practice, most students grasp JS Timers in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now