| Asynchronous JavaScript | Promise in JavaScript | |
setTimeout() and setInterval() in JavaScript |
Let’s dive into two essential asynchronous functions in JavaScript: setTimeout and setInterval. These are built-in timing functions that help schedule tasks.
setTimeout() and setInterval() are web API methods in JavaScript that enable asynchronous execution by scheduling code to run after a delay. The core difference is that setTimeout() runs a function once, while setInterval() runs a function repeatedly.
This method executes a function only once after a specified time delay. It is ideal for actions that should be performed one time in the future.
What it does:
Executes a function once after a specified delay (in milliseconds).
✅ Syntax:
setTimeout(function, delay);
🧪 Example:
console.log("Start");
setTimeout(() => {
console.log("This log appears after 2 seconds.");
}, 2000);
console.log("End");
Start End (After 2 seconds) This log appears after 2 seconds.
In this example, the code is non-blocking. "End" is logged immediately, and the setTimeout callback function is placed in a queue to be run later.
This method repeatedly calls a function with a fixed time delay between each call. The execution continues indefinitely until it is stopped with clearInterval().
What it does:
Executes a function repeatedly at fixed intervals (in milliseconds).
✅ Syntax:
setInterval(function, interval);
🧪 Example:
let count = 0;
const intervalID = setInterval(() => {
count++;
console.log(`Interval executed: ${count}`);
if (count === 4) {
clearInterval(intervalID);
console.log("Interval stopped.");
}
}, 1000);
(After 1s) Interval executed: 1 (After 2s) Interval executed: 2 (After 3s) Interval executed: 3 (After 4s) Interval executed: 4 (After 4s) Interval stopped.
This is useful for tasks like a digital clock or a progress bar.
| Aspect | setTimeout() | setInterval() |
|---|---|---|
| Advantages | More precise control, avoids "pile-up" issue. | Simple for fixed interval repetition. |
| Disadvantages | More verbose for repetition. | Can cause overlapping executions. |
| Method | When to Use |
|---|---|
| setTimeout() | One-off delays, repeated tasks with control, debouncing/throttling. |
| setInterval() | Simple, fixed interval tasks like counters. |
| Method | Avoid When |
|---|---|
| setTimeout() | For very simple repetitive tasks. |
| setInterval() | For long/complex repeated tasks or animations. |
| Feature | setTimeout | setInterval |
|---|---|---|
| Runs how often | Once | Repeatedly |
| Use case | Delay execution | Repeat execution |
| Cancel method | clearTimeout(id) | clearInterval(id) |
| Asynchronous JavaScript | Promise in JavaScript | |