JS setTimeout and setInterval
In this page:
setTimeout()
setTimeout() schedules a function to run after a delay. The delay is a minimum, not a guarantee — if the call stack is busy, the callback waits until JavaScript is free to run it, even after the delay has passed.
Example: setTimeout()
setTimeout(() => {
console.log("Runs after at least 1 second");
}, 1000);
Passing Arguments
You can pass arguments to a function scheduled by setTimeout(). Any arguments after the delay are passed through to the callback function when it eventually runs, avoiding the need for an extra wrapper closure.
Example: Passing Arguments
setTimeout((name) => {
console.log("Hello, " + name);
}, 500, "Sam");
clearTimeout()
clearTimeout() cancels a timeout before it runs. Calling clearTimeout() before the delay elapses prevents the scheduled callback from ever running, which is essential for cleanup when a component unmounts or a user cancels an action.
Example: clearTimeout()
const id = setTimeout(() => console.log("This will never run"), 1000);
clearTimeout(id);
setInterval()
setInterval() repeats a function after every given delay. Unlike setTimeout's one-time delay, setInterval() keeps invoking the callback repeatedly at that interval until something explicitly stops it.
Example: setInterval()
let count = 0;
const id = setInterval(() => {
count++;
console.log(count);
}, 500);
clearInterval()
clearInterval() stops a repeating timer. Forgetting to clear an interval is a common source of memory leaks and unwanted background work, so every setInterval() should have a matching clearInterval() somewhere.
Example: clearInterval()
let count = 0;
const id = setInterval(() => {
count++;
console.log(count);
if (count === 3) clearInterval(id);
}, 300);
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML