Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - Using setTimeout()
  • - Using setInterval()
  • - Canceling a Timeout
  • - Mini Challenge

13. Timers and Intervals

Level: BeginnerDuration: 11m

Sometimes, you want your code to run **after a delay** or **every few seconds** — like showing a message later, or updating a clock. JavaScript has two powerful tools for this: `setTimeout()` and `setInterval()`.

Using setTimeout()

javascript
console.log('Waiting...');

setTimeout(() => {
  console.log('3 seconds passed!');
}, 3000);

`setTimeout()` runs the function **once** after the specified delay (in milliseconds). In this example, the message appears after 3 seconds.

Using setInterval()

javascript
let count = 1;

const timer = setInterval(() => {
  console.log('Tick', count);
  count++;

  if (count > 5) {
    clearInterval(timer);
    console.log('Stopped!');
  }
}, 1000);

`setInterval()` repeats the function every given number of milliseconds until you stop it using `clearInterval()`.

Canceling a Timeout

javascript
const alertTimeout = setTimeout(() => {
  alert('You stayed too long!');
}, 5000);

// Cancel it if user leaves early
clearTimeout(alertTimeout);

Both `setTimeout()` and `setInterval()` return an ID. You can store it in a variable and pass it to `clearTimeout()` or `clearInterval()` to stop it.

Mini Challenge

Create a countdown from 5 to 0 that updates the page every second using `setInterval()`. When it hits 0, display “Time’s up!” and stop the timer.

MDN Docs: setTimeout() and setInterval()