SetTimeout vs setInterval in JavaScript: Key Differences and Usage
setTimeout runs a function once after a specified delay, while setInterval runs a function repeatedly at fixed intervals. Use setTimeout for one-time delays and setInterval for repeated actions.Quick Comparison
Here is a quick side-by-side comparison of setTimeout and setInterval based on key factors.
| Factor | setTimeout | setInterval |
|---|---|---|
| Purpose | Runs a function once after delay | Runs a function repeatedly at intervals |
| Execution | Single delayed execution | Repeated executions until stopped |
| Return Value | Timeout ID (for canceling) | Interval ID (for canceling) |
| Use Case | One-time delay tasks | Periodic or repeated tasks |
| Stopping | clearTimeout(timeoutID) | clearInterval(intervalID) |
| Behavior if callback takes longer than delay | Next call delayed accordingly | Calls may queue or overlap |
Key Differences
setTimeout schedules a function to run once after a specified number of milliseconds. After the delay, the function executes a single time and then stops automatically. You can cancel it before it runs using clearTimeout with the returned timeout ID.
In contrast, setInterval schedules a function to run repeatedly every specified number of milliseconds. It keeps running the function at fixed intervals until you stop it with clearInterval using the interval ID it returns.
Another important difference is how they behave if the callback function takes longer to execute than the delay or interval. setTimeout waits for the function to finish before scheduling the next call if you manually call it again, while setInterval keeps firing at fixed intervals, which can cause overlapping calls if the function is slow.
Code Comparison
This example shows how to use setTimeout to print "Hello" once after 2 seconds.
setTimeout(() => { console.log('Hello'); }, 2000);
setInterval Equivalent
This example uses setInterval to print "Hello" every 2 seconds repeatedly.
const intervalId = setInterval(() => { console.log('Hello'); }, 2000); // To stop after 6 seconds: setTimeout(() => { clearInterval(intervalId); console.log('Stopped'); }, 6000);
When to Use Which
Choose setTimeout when you want to delay a task just once, like showing a message after a pause or delaying an action. Choose setInterval when you need to repeat a task regularly, such as updating a clock, polling data, or animating something continuously. Remember to always clear intervals when no longer needed to avoid unwanted repeated actions.
Key Takeaways
setTimeout runs a function once after a delay; setInterval runs repeatedly at intervals.clearTimeout and clearInterval to stop scheduled actions.setInterval can cause overlapping calls if the callback is slow; setTimeout avoids this by running once.setTimeout for one-time delays and setInterval for repeated tasks.