Scheduling in JavaScript: setTimeout & setInterval
JavaScript provides two main scheduling functions to execute code after a delay or repeatedly at intervals:
setTimeout→ Runs a function once after a delay.setInterval→ Runs a function repeatedly at fixed intervals.
1️⃣ setTimeout – Delayed Execution
setTimeout executes a function after a specified time (in milliseconds).
Syntax
function→ Function to executedelay→ Time in milliseconds (1 second = 1000 ms)param1, param2, ...→ Optional parameters for the function
Example: Delay Execution by 2 Seconds
Example: Passing Arguments
Cancel setTimeout with clearTimeout
If you need to cancel a scheduled timeout, use clearTimeout.
2️⃣ setInterval – Repeated Execution
setInterval executes a function at regular intervals (repeats indefinitely).
Syntax
function→ Function to executeinterval→ Time interval in millisecondsparam1, param2, ...→ Optional parameters
Example: Run Every 1 Second
Example: Passing Arguments
Cancel setInterval with clearInterval
To stop a repeating interval, use clearInterval.
3️⃣ When to Use setTimeout vs. setInterval?
| Feature | setTimeout | setInterval |
|---|---|---|
| Runs once? | ✅ Yes | ❌ No (Repeats) |
| Runs repeatedly? | ❌ No | ✅ Yes |
| Can be canceled? | ✅ clearTimeout() | ✅ clearInterval() |
| Best for? | Delayed execution | Periodic updates |
4️⃣ Alternative to setInterval – Recursive setTimeout
A better alternative to setInterval is using recursive setTimeout, which ensures accurate timing.
✅ Why use this?
- Prevents overlapping executions if a previous task is still running.
- More accurate than
setIntervalfor long tasks.
Conclusion
✔ setTimeout → Executes a function once after a delay.
✔ setInterval → Repeats execution at fixed intervals.
✔ Use clearTimeout / clearInterval to cancel scheduled tasks.
✔ For more control, use recursive setTimeout instead of setInterval.
🚀 Need more examples? Let me know! 😃

