JavaScript provides built-in timer functions:
- ✅ setTimeout() – Run once after a delay
- ✅ setInterval() – Run repeatedly at a fixed interval
setTimeout() – Single-Execution Timer
Executes a function once after a specified time.
Syntax
setTimeout(function, delayInMilliseconds);
Example
setTimeout(function () {
console.log("Executed after 3 seconds");
}, 3000);
📌 Use case:
- Delay showing a message
- Auto logout after inactivity
- Redirect after success message
setInterval() – Repeating Timer
Executes a function continuously at a fixed interval.
Syntax
setInterval(function, intervalInMilliseconds);
Example
setInterval(function () {
console.log("Runs every 2 seconds");
}, 2000);
📌 Use case:
- Refresh data
- Poll API
- Update clock / timer
How to Set Time Interval for the Next Call
Option 1: Using setInterval()
Best when the interval is fixed.
setInterval(fetchData, 5000);
function fetchData() {
console.log("API called every 5 seconds");
}
Option 2: Using Recursive setTimeout() (Recommended)
Best when you need dynamic control over the next execution.
function callApi() {
console.log("API called");
setTimeout(callApi, 3000);
}
callApi();
📌 Why use this?
- Prevents overlapping calls
- Waits for execution to finish
- Ideal for API polling
Stop or Clear Timers
Stop setTimeout
let timerId = setTimeout(() => {
console.log("Will not execute");
}, 3000);
clearTimeout(timerId);
Stop setInterval
let intervalId = setInterval(() => {
console.log("Running...");
}, 2000);
clearInterval(intervalId);
Real-World Example: API Polling Every 5 Seconds
function pollServer() {
fetch('/api/status')
.then(response => response.json())
.then(data => {
console.log(data);
setTimeout(pollServer, 5000);
});
}
pollServer();
✔ Avoids duplicate calls
✔ Executes after response completes
Summary Table
| Method | Executes | Best Use Case |
|---|---|---|
| setTimeout | Once | Delay action |
| setInterval | Repeat | Fixed interval |
| Recursive setTimeout | Repeat | Controlled interval |
Interview Tip 💡
Prefer setTimeout recursion over setInterval for API calls to avoid overlapping executions.
.jpg)
.jpg)


.jpg)



.png)