J

JavaScript Handbook

Clean • Professional

Timing Methods in JavaScript

2 minute

Timing Methods

JavaScript provides built-in timing functions that allow you to schedule code execution after a delay or repeatedly at fixed intervals. These functions are part of the Browser Object Model (BOM) and are accessible via the window object.

The two main timing methods are:

  1. setTimeout() – Run a function once after a delay.
  2. setInterval() – Run a function repeatedly at fixed intervals.

setTimeout() – Execute Once After Delay

The setTimeout() method calls a function once after a specified number of milliseconds.

Syntax:

const timeoutId = setTimeout(function, delay, param1, param2, ...);
  • function – The function to execute.
  • delay – Time in milliseconds to wait before execution.
  • Optional parameters – Arguments passed to the function.
  • Returns a timeout ID, which can be used to cancel it with clearTimeout().

Example:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

// Run greet() after 2 seconds
const timeoutId = setTimeout(greet, 2000, "Alice");

Canceling a Timeout:

  • Schedules code to run once after a delay.
  • Useful for delaying execution or creating timed events.
clearTimeout(timeoutId);

setInterval() – Execute Repeatedly

The setInterval() method calls a function repeatedly at fixed time intervals.

Syntax:

const intervalId = setInterval(function, interval, param1, param2, ...);
  • function – The function to execute.
  • interval – Time in milliseconds between each execution.
  • Returns an interval ID, which can be used to cancel it with clearInterval().

Example:

function showTime() {
  const now = new Date();
  console.log(`Current time: ${now.toLocaleTimeString()}`);
}

// Run showTime() every 1 second
const intervalId = setInterval(showTime, 1000);

Canceling an Interval:

  • Continuously executes code at regular intervals.
  • Useful for clocks, animations, polling, or repeated updates.
clearInterval(intervalId);

Practical Examples

Example 1 – Delayed Alert:

setTimeout(() => {
  alert("This message appears after 3 seconds!");
}, 3000);

Example 2 – Countdown Timer:

let count = 5;
const countdown = setInterval(() => {
  console.log(count);
  count--;
  if(count < 0) {
    clearInterval(countdown);
    console.log("Time's up!");
  }
}, 1000);

Example 3 – Passing Parameters:

function greetUser(name) {
  console.log(`Hello, ${name}!`);
}

setTimeout(greetUser, 2000, "Bob"); // Executes after 2 seconds

 

Article 0 of 0