← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 6 of 26

JS setTimeout and setInterval

setTimeout()

setTimeout() schedules a function to run after a delay. The delay is a minimum, not a guarantee — if the call stack is busy, the callback waits until JavaScript is free to run it, even after the delay has passed.

Example: setTimeout()

javascript
setTimeout(() => {
  console.log("Runs after at least 1 second");
}, 1000);

Passing Arguments

You can pass arguments to a function scheduled by setTimeout(). Any arguments after the delay are passed through to the callback function when it eventually runs, avoiding the need for an extra wrapper closure.

Example: Passing Arguments

javascript
setTimeout((name) => {
  console.log("Hello, " + name);
}, 500, "Sam");

clearTimeout()

clearTimeout() cancels a timeout before it runs. Calling clearTimeout() before the delay elapses prevents the scheduled callback from ever running, which is essential for cleanup when a component unmounts or a user cancels an action.

Example: clearTimeout()

javascript
const id = setTimeout(() => console.log("This will never run"), 1000);
clearTimeout(id);

setInterval()

setInterval() repeats a function after every given delay. Unlike setTimeout's one-time delay, setInterval() keeps invoking the callback repeatedly at that interval until something explicitly stops it.

Example: setInterval()

javascript
let count = 0;
const id = setInterval(() => {
  count++;
  console.log(count);
}, 500);

clearInterval()

clearInterval() stops a repeating timer. Forgetting to clear an interval is a common source of memory leaks and unwanted background work, so every setInterval() should have a matching clearInterval() somewhere.

Example: clearInterval()

javascript
let count = 0;
const id = setInterval(() => {
  count++;
  console.log(count);
  if (count === 3) clearInterval(id);
}, 300);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.