learn2kode.in

JavaScript Timers Tutorial: setTimeout and setInterval Explained

JavaScript timers allow you to execute code after a delay or repeat code at regular intervals. They are commonly used for animations, notifications, auto-refresh features, countdowns, and real-time updates.

JavaScript provides two main timer functions:

1. How to Use setTimeout in JavaScript setTimeout()

The setTimeout() function executes a function one time after a specified number of milliseconds.

Syntax

setTimeout(function, delay);

JavaScript setInterval Examples

setTimeout(() => {
  console.log("Hello after 2 seconds!");
}, 2000);
This message appears after 2 seconds.

Clearing setTimeout

You can cancel a timeout before it runs using clearTimeout().
const timerId = setTimeout(() => {
  console.log("This will not run");
}, 3000);

clearTimeout(timerId);

2. setInterval() – JavaScript Delay and Interval Functions

The setInterval() function executes code again and again at a fixed time interval.

Syntax

setInterval(function, interval);

Example

setInterval(() => {
  console.log("Runs every second");
}, 1000);
This runs every 1 second until stopped.

Clearing setInterval

Use clearInterval() to stop the interval.

const intervalId = setInterval(() => {
  console.log("Running...");
}, 1000);

clearInterval(intervalId);

Common Use Cases of Timers

Countdown Example

let count = 5;

const countdown = setInterval(() => {
  console.log(count);
  count--;

  if (count < 0) {
    clearInterval(countdown);
    console.log("Time's up!");
  }
}, 1000);

setTimeout vs setInterval

Feature setTimeout setInterval
Execution Runs once Runs repeatedly
Use Case Delayed action Repeated task
Stop Method clearTimeout() clearInterval()
Example Popup after delay Live clock

Important Notes

Best Practice Tip

Instead of:
Use:
function repeat() {
  fn();
  setTimeout(repeat, 1000);
}
repeat();
This avoids overlapping executions.

Summary