JavaScript Timing Events

setTimeout

The setTimeout() function allows you to execute code once after a specified delay:

setTimeout(function() {
  alert("This appears after 2 seconds");
}, 2000);

The delay is in milliseconds. 1000 ms = 1 second.

setInterval

The setInterval() function repeatedly runs a block of code every defined number of milliseconds:

const intervalId = setInterval(() => {
  console.log("Repeating every 1 second");
}, 1000);

Clearing Timers

Use the returned timer ID to stop the execution of the timer:

const timeoutId = setTimeout(() => {
  console.log("You won't see this.");
}, 5000);

clearTimeout(timeoutId);  // Cancels the timeout

clearInterval(intervalId);  // Stops the interval

Practical Examples

  • Show tooltips after a delay
  • Create a countdown timer
  • Poll the server for new data
  • Delay a redirect or animation
let count = 3;
const countdown = setInterval(() => {
  console.log(count--);
  if (count < 0) clearInterval(countdown);
}, 1000);

Best Practices

  • Store timer IDs in variables if you need to cancel them
  • Clear intervals to prevent memory leaks or unwanted repetition
  • For animation loops, use requestAnimationFrame instead of setInterval for smoother performance

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic