1. Timing Methods Overview
Executes a function once after a specified delay (in milliseconds).
Returns a timeout ID that can be used to cancel the execution.
Repeatedly executes a function at specified time intervals (in milliseconds).
Returns an interval ID that can be used to stop the execution.
Stops the execution of setTimeout() or setInterval() using their returned IDs.
Essential for managing and cleaning up timers.
Optimized for animations. Runs before the next repaint (usually 60fps).
Better performance than setInterval for animations.
Timing Events Output
[Ready]
π Click any timing button to see results here
2. Timer Visualization
3. Countdown Timer Demo
Countdown Timer
10:00
Ready to start
// Countdown Timer Implementation
class CountdownTimer {
constructor(seconds) {
this.totalSeconds = seconds;
this.remainingSeconds = seconds;
this.timerId = null;
this.isRunning = false;
}
start() {
if (this.isRunning) return;
this.isRunning = true;
this.timerId = setInterval(() => {
this.remainingSeconds--;
this.updateDisplay();
if (this.remainingSeconds <= 0) {
this.stop();
alert("Time's up!");
}
}, 1000);
}
pause() {
this.isRunning = false;
clearInterval(this.timerId);
}
reset() {
this.pause();
this.remainingSeconds = this.totalSeconds;
this.updateDisplay();
}
updateDisplay() {
const minutes = Math.floor(this.remainingSeconds / 60);
const seconds = this.remainingSeconds % 60;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
}
4. Stopwatch Demo
Stopwatch
00:00.00
Ready
No lap times recorded yet
5. Real-World Examples
// Real-world timing implementations
// 1. Debounce - delays execution until after wait time
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// 2. Throttle - limits execution to once per period
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// 3. Polling - checks for updates periodically
function startPolling(url, interval, callback) {
const poll = () => {
fetch(url)
.then(response => response.json())
.then(data => callback(data));
};
poll(); // Immediate first call
return setInterval(poll, interval);
}
6. Scheduled Task Manager
No scheduled tasks. Schedule some tasks above!
7. Timing Methods Comparison
| Method |
Execution |
Returns |
Cancellation |
Use Case |
Performance |
| setTimeout() |
Once after delay |
Timeout ID |
clearTimeout(id) |
Delayed actions, debouncing |
βοΈβοΈβοΈβοΈ |
| setInterval() |
Repeatedly at intervals |
Interval ID |
clearInterval(id) |
Clocks, polls, animations |
βοΈβοΈβοΈ |
| requestAnimationFrame() |
Before next repaint |
Animation ID |
cancelAnimationFrame(id) |
Smooth animations |
βοΈβοΈβοΈβοΈβοΈ |
| setImmediate() |
Next event loop cycle |
Immediate ID |
clearImmediate(id) |
Non-blocking execution |
βοΈβοΈβοΈβοΈ |
| Promise.resolve().then() |
Microtask queue |
Promise |
N/A |
Async operations |
βοΈβοΈβοΈβοΈβοΈ |
// Best Practices for Timing Events
// 1. Always clear timers when done
let timerId = setTimeout(() => {
console.log("Done");
}, 1000);
// Clean up if component unmounts
// clearTimeout(timerId);
// 2. Avoid memory leaks with intervals
const intervalId = setInterval(() => {
// Your code
}, 1000);
// Clear when no longer needed
// clearInterval(intervalId);
// 3. Use requestAnimationFrame for animations
function animate() {
// Animation logic
animationId = requestAnimationFrame(animate);
}
// Stop animation when done
// cancelAnimationFrame(animationId);
// 4. Be careful with recursive setTimeout
function recursiveTimeout() {
// Do work
setTimeout(recursiveTimeout, 1000);
}
// 5. Handle page visibility changes
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
// Pause timers
} else {
// Resume timers
}
});