JS DOM: setTimeout, setInterval

By Xah Lee. Date: . Last updated: .

What is setTimeout and setInterval

setTimeout and setInterval lets you call a function after a delay, or call it repeatedly. They are essential for animations, auto-saving, countdowns, etc.

setTimeout

setTimeout(f, delayInMilliseconds, args)

call a function after a delay.

  • f → Function to run.
  • delayInMilliseconds → delay, in milliseconds.
  • args → Optional arguments passed to f.
  • Return a id, for removing the timeout, by clearTimeout(id).
setTimeout(() => {
  console.log("hi after 2 seconds!");
}, 2000);

Example. Pass arguments to function.

const ff = (name) => {
 console.log(`hello ${name}.`);
};

setTimeout(ff, 1000, "Alice");
// hello Alice.

setInterval. Run Repeatedly

setInterval(f, delayInMilliseconds, args)

call a function at every time interval.

  • f → Function to run.
  • delayInMilliseconds → interval in milliseconds.
  • args → Optional arguments passed to f.
  • Return a id, for removing the timeout, by clearInterval(id).
let count = 0;
const intervalId = setInterval(() => {
 count++;
 console.log(`Count: ${count}`);

 if (count >= 5) {
  clearInterval(intervalId);
  console.log("Stopped");
 }
}, 1000);

/*
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Stopped
*/

Clear Timer

use these to remove timer.

clearTimeout(id)

clearInterval(id)

Example of canceling

const id = setTimeout(() => console.log("This won't run"), 5000);

// Cancel immediately
clearTimeout(id);

🟢 TIP: you can call clearTimeout on an interval ID and vice versa (they share the same ID pool), but it's best practice to use the matching clear function.

Example. Debouncing User Input (common in search boxes)

let timeout;
const input = document.getElementById('search');

input.addEventListener('input', () => {
  clearTimeout(timeout); // cancel previous

  timeout = setTimeout(() => {
    console.log("Searching for:", input.value);
    // perform expensive search
  }, 300); // wait until user stops typing
});

Warning and tips

Problem with thisBinding

🛑 WARNING: if the function argument uses this (binding) and is passed in the form of object.method, the thisBinding becomes undefined. To make it work, wrap it in Arrow Function .

const xobj = {
 name: "Joe",
 greet() {
  console.log("name is:", this.name);
 },
};

// Wrong
setTimeout(xobj.greet, 1000);
// name is:

// Correct way
setTimeout(() => xobj.greet(), 1000);
// name is: Joe

Minimum delay and throttling

Browsers clamp delays below 4ms to 4ms for setTimeout/setInterval when called from the main thread after the first execution. Nested timers have even higher minimums (for security/performance).

Not precise timing

Timers are not guaranteed to fire exactly on time. They are scheduled when the event loop is free. Heavy computation or long tasks delay them.

Modern alternatives