Timing Functions

Use setTimeout and setInterval for timing operations and animations.

Present State

Timing functions in JavaScript allow execution of code after a delay or at regular intervals. The two most commonly used functions are setTimeout(), which runs code once after a delay, and setInterval(), which runs code repeatedly at specified intervals. These functions are essential for animations, polling data, or scheduling tasks in web applications.

Code Example

Examples of using setTimeout and setInterval:

setTimeout and setInterval

// setTimeout - runs once after 2 seconds
setTimeout(() => {
  console.log("Executed after 2 seconds");
}, 2000);

// setInterval - runs every 1 second
const intervalId = setInterval(() => {
  console.log("Runs every second");
}, 1000);

// Clear the interval after 5 seconds
setTimeout(() => {
  clearInterval(intervalId);
  console.log("Interval cleared");
}, 5000);
          

This code demonstrates:

  • Using setTimeout to delay code execution.
  • Using setInterval for repeated execution.
  • Using clearInterval to stop repeated execution.

Description

setTimeout() and setInterval() are asynchronous functions that control timing in JavaScript.

  • setTimeout(callback, delay): Executes the callback function once after delay milliseconds.
  • setInterval(callback, delay): Repeatedly executes the callback every delay milliseconds.
  • clearTimeout(timeoutId): Cancels a timeout set by setTimeout.
  • clearInterval(intervalId): Stops an interval set by setInterval.

These timing methods are commonly used in creating animations, scheduling API requests, or deferring execution of heavy computations.

Applications

  • Creating simple animations and transition effects.
  • Implementing countdown timers.
  • Polling APIs for real-time updates.
  • Delaying execution for UX improvements (e.g., loading spinners).
  • Scheduling periodic background tasks in JavaScript apps.

Multiple Choice Questions

Q1: Which function is used to execute a task after a delay?

  • A. setInterval
  • B. delay
  • C. wait
  • D. setTimeout

Answer: D. setTimeout

Q2: What does clearInterval do?

  • A. Delays a function call
  • B. Clears a delayed task
  • C. Stops a repeating interval
  • D. Restarts an interval

Answer: C. Stops a repeating interval

Q3: What is returned by setTimeout and setInterval?

  • A. A timer name
  • B. A delay value
  • C. A callback reference
  • D. A unique ID

Answer: D. A unique ID

Q4: How can you stop a setTimeout before it runs?

  • A. clearTimeout(id)
  • B. stopTimeout()
  • C. clearDelay()
  • D. cancelTimeout()

Answer: A. clearTimeout(id)