JavaScript Timers

1. What are Timers?

JavaScript timers are methods that allow you to execute a piece of code at a specific time or at repeated intervals. They are a fundamental part of asynchronous JavaScript, enabling tasks to be scheduled without blocking the main thread.

2. setTimeout

The setTimeout() method executes a function or a specified piece of code once after a specified delay (in milliseconds).

document.write("Start");

setTimeout(() => {
    document.write("Executed after 2 seconds");
}, 2000); // 2000 ms = 2 seconds

document.write("End"); // This logs before the timeout
        

3. setInterval

The setInterval() method repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

let intervalId = setInterval(() => {
    document.write("Executed every 1 second");
}, 1000);

// Stop interval after 5 seconds
setTimeout(() => {
    clearInterval(intervalId);
    document.write("Interval stopped.");
}, 5000);
        

4. Example: Timer Demo

This example demonstrates a simple counter using setInterval and clearInterval.

0

5. Comparison Table: setTimeout vs setInterval

Function Purpose Stop Method Use Case
setTimeout Executes a function once after a delay. clearTimeout Showing a popup after 5 seconds.
setInterval Executes a function repeatedly at a set interval. clearInterval Updating a clock every second.
Best Practice: Always assign the result of setInterval or setTimeout to a variable so you can clear it later using clearInterval() or clearTimeout() to prevent memory leaks.

Practice Questions

Test your understanding of JavaScript Timers.

Easy

Q1: Create a basic timeout.

  • Write a setTimeout function.
  • Pass a callback function that logs "Hello World!" to the console.
  • Set the delay to 3 seconds (3000 milliseconds).
Easy

Q2: Stop a running interval.

  • Assume you have a running interval: let myInterval = setInterval(..., 1000);.
  • Write the correct JavaScript method to stop this interval from executing further.
Medium

Q3: Create a recurring timer.

  • Write a setInterval function.
  • Inside the callback, get the current time using new Date().toLocaleTimeString().
  • Log the current time to the console.
  • Set the interval to repeat every 2 seconds.
Medium

Q4: Cancel a timeout before it executes.

  • Create a setTimeout that logs a message after 5 seconds.
  • Store the timeout ID in a variable named myTimeout.
  • Write the code to cancel this timeout immediately so the message never logs.
Hard

Q5: Create a countdown timer.

  • Write a function named countdown that accepts a seconds parameter.
  • Use setInterval to decrease the seconds by 1 every second and log the remaining time.
  • When the seconds reach 0, clear the interval and log "Done!" to the console.

Answer

Code: