0% found this document useful (0 votes)
6 views

JavaScript_Timers

Java script interview questions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

JavaScript_Timers

Java script interview questions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

JavaScript Timers: setTimeout() vs setInterval()

JavaScript Timers for Beginners

1. setTimeout() - Run code once after a delay

Use this when you want to delay a task.

Example:

setTimeout(() => {

console.log("Hello after 3 seconds");

}, 3000);

What it does:

- Waits 3 seconds

- Then runs the function once

2. setInterval() - Run code repeatedly

Use this when you want to repeat something every few seconds.

Example:

setInterval(() => {

console.log("Repeating every 2 seconds");

}, 2000);

What it does:

- Runs the function

- Again and again, every 2 seconds

@the_coder_dex
JavaScript Timers: setTimeout() vs setInterval()

How to stop them?

const timer = setTimeout(() => {}, 5000);

clearTimeout(timer); // Cancels setTimeout

const interval = setInterval(() => {}, 1000);

clearInterval(interval); // Cancels setInterval

Real-life uses:

- setTimeout: Show a message after a delay

- setInterval: Countdown timers, clocks, animations

Quick Tip:

setTimeout = "do it later"

setInterval = "keep doing it"

@the_coder_dex

You might also like