Secure & Private (Zero Data Retention)
Free Access • No Sign-Up
Timers & Timing
Timers allow you to execute code after a specified delay or repeatedly on an interval.
Try It Yourself
📋 Copy Debounce and Throttle Implementation Snippet
// Debounce Function (Collapses Rapid Calls into One)
function debounce(fn, delayMs = 300) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn.apply(this, args), delayMs);
};
}
// Throttle Function (Limits Execution to Rate Interval)
function throttle(fn, limitMs = 300) {
let inThrottle;
return function (...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limitMs);
}
};
}
⚠️ 5 Fatal Traps & JavaScript Pitfalls
Trap #1: Forgetting to Clear Timers on Unmount
Failing to call clearTimeout or clearInterval leaves callbacks referencing unmounted DOM elements, leaking memory and throwing errors.
Trap #2: Background Tab Timer Clamping
Browsers throttle setTimeout and setInterval to 1,000ms or slower in inactive background tabs to save battery. Never rely on timers for precise audio or game timing.
Trap #3: Timer Drift from Event Loop Queuing
Timers specify the MINIMUM delay before the callback is queued, not exact execution time. Heavy synchronous tasks delay timer execution.
Trap #4: Passing Strings to setTimeout (Implicit eval)
Writing setTimeout("doSomething()", 100) invokes eval() behind the scenes, creating a security risk and degrading optimization.
Trap #5: setTimeout(fn, 0) Is Still Asynchronous
Even with a delay of 0, the callback is queued into the macrotask queue and executes only AFTER all current synchronous code and microtasks complete.
💬 Frequently Asked Questions
What is the practical difference between debounce and throttle?
Debounce waits for a pause in activity before executing (e.g. search autocomplete). Throttle guarantees execution at a steady maximum rate (e.g. window resize or scroll handlers).
What is requestAnimationFrame() and why is it superior for animations?
requestAnimationFrame() syncs with the browser display refresh rate (typically 60Hz/120Hz), pauses in background tabs, and prevents screen tearing and unnecessary CPU load.
What does queueMicrotask() do?
queueMicrotask() schedules a callback to run immediately after the current synchronous function finishes, before UI rendering or macrotask timers execute.
Why can timer intervals stack up with setInterval?
If the callback takes longer to execute than the interval delay, multiple executions can queue consecutively without gaps. Use recursive setTimeout instead.
What does clearTimeout(undefined) do?
Calling clearTimeout(null) or clearTimeout(undefined) fails silently without throwing an error.