setTimeout, setInterval, requestAnimationFrame: Key differences and use cases

Day 25/50 – JavaScript Interview Question? Question: What is the difference between setTimeout(), setInterval(), and requestAnimationFrame()? Simple Answer: setTimeout() executes code once after a delay. setInterval() repeats execution at fixed intervals. requestAnimationFrame() executes before the next browser repaint, synchronized with the display refresh rate (~60fps). 🧠 Why it matters in real projects: setTimeout is for delayed actions (toast notifications), setInterval for polling (though not recommended), and requestAnimationFrame for smooth animations. Using the wrong one causes janky animations, wasted CPU, or incorrect timing. 💡 One common mistake: Using setInterval() for animations instead of requestAnimationFrame(), which wastes resources when the tab is inactive and doesn't sync with screen refreshes. 📌 Bonus: // setTimeout - run once setTimeout(() => { console.log('Executed after 2 seconds'); }, 2000); // setInterval - repeats (problematic!) const intervalId = setInterval(() => { console.log('Every second'); }, 1000); clearInterval(intervalId); // Don't forget to clear! // requestAnimationFrame - smooth animations function animate() { // Update animation state element.style.left = position + 'px'; position += 2; if (position < 500) { requestAnimationFrame(animate); // Loop } } requestAnimationFrame(animate); // Why RAF is better: // ✓ Pauses when tab is inactive (saves CPU) // ✓ Syncs with screen refresh (60fps) // ✓ Better performance than setInterval // Modern polling with recursive setTimeout function poll() { fetchData().then(() => { setTimeout(poll, 5000); // Next poll after response }); } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories