← Back to Chapters

JavaScript Timing (setTimeout & setInterval)

⏱️ JavaScript Timing (setTimeout & setInterval)

⚡ Quick Overview

JavaScript provides timing functions that let you run code after a delay or repeatedly at a fixed interval. These are commonly used for animations, scheduled tasks, countdowns, notifications, and small delays in user interfaces.

The main timing functions are setTimeout(), clearTimeout(), setInterval(), and clearInterval().

? Key Concepts

  • setTimeout(fn, delay) – runs a function once after a given delay (in milliseconds).
  • clearTimeout(id) – cancels a timeout created by setTimeout().
  • setInterval(fn, delay) – runs a function repeatedly every given delay.
  • clearInterval(id) – stops an interval created by setInterval().
  • Both setTimeout() and setInterval() return an ID that you must store to cancel them later.
  • Delays are specified in milliseconds (1000 ms = 1 second).

? Summary Table

Function Purpose Runs
setTimeout() Delay execution Once after delay
clearTimeout() Cancel timeout Stops scheduled run
setInterval() Repeat execution Repeatedly
clearInterval() Stop interval Stops repeating

? Syntax & Theory

Basic syntax for JavaScript timing functions:

  • setTimeout(callback, delayInMs, arg1, arg2, ...)
  • setInterval(callback, delayInMs, arg1, arg2, ...)
  • clearTimeout(timeoutId)
  • clearInterval(intervalId)

Timing in JavaScript is not exact. If the main thread is busy, calls may be delayed. Use timing functions for scheduling, animations, UI effects, and background polling—but not for ultra-precise timing.

? Code Examples

⏳ Basic setTimeout alert
<script>
setTimeout(function() {
  alert("This message is shown after 3 seconds");
}, 3000);
</script>
? setTimeout with a named function
<script>
function greet() {
  console.log("Hello after 2 seconds");
}

setTimeout(greet, 2000);
</script>
? Cancelling a timeout with clearTimeout
<script>
let timer = setTimeout(() => {
  console.log("This will not run");
}, 4000);

clearTimeout(timer);
</script>
? setInterval with automatic stop
<script>
let count = 0;
let intervalId = setInterval(() => {
  count++;
  console.log("Count: " + count);
  if (count === 5) {
    clearInterval(intervalId); // stop after 5 times
  }
}, 1000);
</script>
⏲️ Stopping an interval after 6 seconds
<script>
let timer = setInterval(() => {
  console.log("This runs every 2 seconds");
}, 2000);

setTimeout(() => {
  clearInterval(timer);
  console.log("Interval stopped after 6 seconds");
}, 6000);
</script>

? Live Output & Explanation

? What the console shows

  • For the basic setTimeout example, nothing happens immediately. After about 3 seconds, an alert box appears with the message: "This message is shown after 3 seconds".
  • For the greet() example, "Hello after 2 seconds" is logged to the console once, after 2 seconds.
  • For the clearTimeout example, the message inside the timeout never appears because the timeout is cancelled before it runs.
  • For the setInterval count example, the console prints: Count: 1, Count: 2, ... up to Count: 5, once per second, then stops.
  • For the interval + setTimeout example, the console logs "This runs every 2 seconds" repeatedly, and after 6 seconds it logs "Interval stopped after 6 seconds" and stops the interval.

? Interactive Counter Demo

Click the button to start a demo interval that counts up every second and stops at 5.

Current count: 0

This uses setInterval() and clearInterval() behind the scenes.

? Tips & Best Practices

  • Use setTimeout() for one-time delays such as showing a welcome message or hiding a popup.
  • Use setInterval() for repeated actions like timers, clocks, and polling APIs.
  • Always store the return value of setTimeout() or setInterval() so you can cancel it later.
  • Clear intervals and timeouts when they are no longer needed to avoid performance issues and memory leaks.
  • Remember that timing is not perfectly precise—callbacks may be delayed if the main thread is busy.
  • Avoid passing strings to setTimeout() (like "alert('hi')"); always pass a function instead.
  • Use arrow functions for shorter, more readable timer callbacks when appropriate.

? Try It Yourself

  • Create a countdown from 5 to 0 using setInterval(), and stop when it reaches 0.
  • Show a welcome message after 2 seconds using setTimeout() when the page loads.
  • Start an interval that prints the current time every second and stop it after 10 seconds.
  • Make blinking text by toggling the visibility of an element with setInterval().
  • Build a typing animation that reveals letters one by one using a series of setTimeout() calls.
  • Pause and resume a timer using setTimeout() and clearTimeout().
  • Display a progress bar that fills up over 5 seconds using setInterval().
  • Show a notification every minute using setInterval() and stop after 3 notifications.
  • Implement a digital clock that updates every second.
  • Flash the background color of a <div> every half second for 5 seconds.