Facebook Pixel

setTimeout Best Practices in Modern JavaScript

setTimeout is useful but often misused. Here are the best practices to use it correctly.

setTimeout Best Practices in Modern JavaScript

setTimeout is useful but often misused. Here are the best practices to use it correctly and avoid common pitfalls.

1. Do Not Rely on Exact Timing

setTimeout guarantees a minimum delay, not an exact delay. Use Date.now() or performance.now() to measure elapsed time.

2. Always Clear Timers

const id = setTimeout(() => { ... }, 1000); // if no longer needed: clearTimeout(id); `` In React, clean up in `useEffect`: ```js useEffect(() => { const id = setTimeout(() => { ... }, 1000); return () => clearTimeout(id); }, []); `` ### 3. Use `let` in Loops, Not `var` ```js for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); // 0, 1, 2 } `` ### 4. Bind `this` for Method Callbacks ```js setTimeout(obj.method.bind(obj), 1000); // or setTimeout(() => obj.method(), 1000); `` ### 5. Pass Functions, Not Results ```js // bad: calls immediately setTimeout(fn(), 1000); // good: passes the function setTimeout(fn, 1000); setTimeout(() => fn(), 1000); `` ### 6. Use `requestAnimationFrame` for Animations ```js function animate() { // update DOM requestAnimationFrame(animate); } requestAnimationFrame(animate); `` ### 7. Break Long Tasks Into Chunks ```js function chunked(items, size = 100) { let i = 0; function next() { const end = Math.min(i + size, items.length); for (; i < end; i++) process(items[i]); if (i < items.length) setTimeout(next, 0); } next(); } `` ### 8. Use Web Workers for Heavy Computation ```js const worker = new Worker("heavy.js"); `` ### 9. Use `queueMicrotask` for Urgent Work ```js queueMicrotask(() => { ... }); `` ### 10. Use `requestIdleCallback` for Low-Priority Work ```js requestIdleCallback((deadline) => { ... }); `` ### The Takeaway Do not rely on exact timing. Always clear timers. Use `let` in loops. Bind `this` for method callbacks. Pass functions, not results. Use `requestAnimationFrame` for animations. Break long tasks into chunks. Use Web Workers for heavy computation. Use `queueMicrotask` for urgent work and `requestIdleCallback` for low-priority work.

Do not rely on exact timing, always clear timers, use let in loops, bind this for method callbacks, pass functions (not results), use requestAnimationFrame for animations, break long tasks into chunks, and use Web Workers for heavy computation.

Always store the timer ID and call clearTimeout when the timer is no longer needed. In React, clean up in useEffect: return () => clearTimeout(id). Never leave a timer running after a component unmounts.

No. Use requestAnimationFrame instead. It syncs with the browser's refresh rate (usually 60fps), runs before the next paint, and produces smoother animations than setTimeout.

Use extra arguments after the delay: setTimeout(fn, 1000, arg1, arg2). Or use an arrow function: setTimeout(() => fn(arg1, arg2), 1000). Do not call the function directly: setTimeout(fn(arg1), 1000) calls fn immediately.

queueMicrotask(fn). It adds fn to the microtask queue, which the event loop drains before rendering and macrotasks. This is faster than setTimeout(cb, 0) for urgent work.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.