Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 28 - JavaScript setTimeout and setInterval

JavaScript provides setTimeout and setInterval for handling delayed and repeated execution of functions. We have already encountered them in our previous lessons, let's explore them now in detail.


Explanation

  • setTimeout(function, delay): Executes a function once after a specified delay (in milliseconds).
  • setInterval(function, delay): Repeats execution of a function every specified milliseconds until stopped.
  • Use clearTimeout() and clearInterval() to cancel them.

Example 1: setTimeout (Delayed Execution)

console.log("Hello! Wait for 3 seconds...");
setTimeout(() => {
    console.log("3 seconds later...");
}, 3000);
  • Prints "Hello!" immediately, then "3 seconds later..." after 3 seconds.

Example 2: setInterval (Repeated Execution)

let counter = 1;
let intervalId = setInterval(() => {
    console.log(`Counter: ${counter}`);
    counter++;
    if (counter > 5) clearInterval(intervalId); // Stops after 5 executions
}, 1000);
  • Logs Counter: 1, Counter: 2... up to Counter: 5 at 1-second intervals.

Example 3: Stopping setTimeout

let timeoutId = setTimeout(() => {
    console.log("This will not print.");
}, 5000);

clearTimeout(timeoutId); // Cancels the timeout
  • The function is never executed because clearTimeout() was called.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson28-timers.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 28 - Timers</title>
      </head>
      <body>
      <script>
         console.log("Hello! Wait for 3 seconds...");
         setTimeout(() => {
             console.log("3 seconds later...");
         }, 3000);
      
         let counter = 1;
         let intervalId = setInterval(() => {
             console.log(`Counter: ${counter}`);
             counter++;
             if (counter > 5) clearInterval(intervalId);
         }, 1000);
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open Developer Console (F12) to See the Logs.


Experiment

  1. Change setTimeout to 5 seconds.
  2. Modify setInterval to stop after 10 counts instead of 5.
  3. Use clearInterval() inside an event listener (e.g., button click) to stop the interval.

Key Takeaways

  • setTimeout runs a function once after a delay.
  • setInterval repeats execution at set intervals.
  • clearTimeout and clearInterval cancel scheduled executions.