Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the difference between setTimeout() and setInterval() in JavaScript?
JavaScript provides two timing functions: setTimeout() for one-time execution and setInterval() for repeated execution at specified intervals.
setTimeout() Function
setTimeout(function, delay) executes a function once after a specified delay in milliseconds.
Syntax
setTimeout(function, delay); setTimeout(callback, delay, param1, param2, ...);
Example
<html>
<body>
<script>
setTimeout(function() {
console.log('This runs once after 2 seconds');
}, 2000);
console.log('This runs immediately');
</script>
</body>
</html>
This runs immediately This runs once after 2 seconds
setInterval() Function
setInterval(function, delay) executes a function repeatedly at specified intervals until cleared.
Syntax
setInterval(function, delay); setInterval(callback, delay, param1, param2, ...);
Example
<html>
<body>
<script>
let counter = 0;
let intervalId = setInterval(function() {
counter++;
console.log('Count:', counter);
if (counter === 3) {
clearInterval(intervalId);
console.log('Interval cleared');
}
}, 1000);
</script>
</body>
</html>
Count: 1 Count: 2 Count: 3 Interval cleared
Clearing Timers
Both functions return an ID that can be used to cancel them:
<html>
<body>
<script>
// Clear timeout before it executes
let timeoutId = setTimeout(() => {
console.log('This will not run');
}, 2000);
clearTimeout(timeoutId);
// Clear interval
let intervalId = setInterval(() => {
console.log('Repeating...');
}, 1000);
setTimeout(() => {
clearInterval(intervalId);
console.log('Interval stopped');
}, 3500);
</script>
</body>
</html>
Repeating... Repeating... Repeating... Interval stopped
Comparison
| Function | Execution | Clearing Method | Use Case |
|---|---|---|---|
setTimeout() |
Once after delay | clearTimeout() |
Delayed actions, debouncing |
setInterval() |
Repeats every interval | clearInterval() |
Periodic updates, animations |
Key Points
-
setTimeout()executes once;setInterval()repeats indefinitely - Both are non-blocking and asynchronous
- Always clear intervals to prevent memory leaks
- Delays are minimum times, not guaranteed exact timing
Conclusion
Use setTimeout() for one-time delayed execution and setInterval() for repeated actions. Always remember to clear intervals when no longer needed.
Advertisements
