🇬🇧 Limited Time — UK Only·🎓 Free Learning for 1 Month·🤖 Free AI Training Included·📚 4,000+ Lessons · 35,000+ Quizzes·🏆 GCSE Mocks · Olympiad Papers·⚡ Selected Students Only · Limited Places·🎁 Free Value Worth £2,000·🇬🇧 Limited Time — UK Only·🎓 Free Learning for 1 Month·🤖 Free AI Training Included·📚 4,000+ Lessons · 35,000+ Quizzes·🏆 GCSE Mocks · Olympiad Papers·⚡ Selected Students Only · Limited Places·🎁 Free Value Worth £2,000·🇬🇧 Limited Time — UK Only·🎓 Free Learning for 1 Month·🤖 Free AI Training Included·📚 4,000+ Lessons · 35,000+ Quizzes·🏆 GCSE Mocks · Olympiad Papers·⚡ Selected Students Only · Limited Places·🎁 Free Value Worth £2,000·
JavaScript

setTimeout and setInterval

📚 What are setTimeout and setInterval? setTimeout() schedules a function to run once after a delay (in milliseconds). setInterval() schedules a function to repeat every N milliseconds until cleared. Both are essential for animations, countdowns, polling, and any time-based behaviour.

8 min 10 XP Lesson 20 of 21
setTimeout and setInterval

📚 What are setTimeout and setInterval?
setTimeout() schedules a function to run once after a delay (in milliseconds). setInterval() schedules a function to repeat every N milliseconds until cleared. Both are essential for animations, countdowns, polling, and any time-based behaviour.

✅ Why they matter
• Create countdowns, delays, and animations in the browser
• Poll a server for updates (though WebSockets are better for real-time)
• Debounce: delay search until the user stops typing
• Auto-dismiss notifications after 3 seconds

🌍 Real-world examples
• setTimeout(() => setToast(null), 3000) dismisses a notification
• setInterval(() => updateClock(), 1000) ticks a digital clock every second
• setTimeout(submit, 500) debounces a search input

💡 Key facts
• setTimeout(fn, ms): run fn once after ms milliseconds
• setInterval(fn, ms): run fn every ms milliseconds until cleared
• Both return an ID you can use to cancel them
• clearTimeout(id) / clearInterval(id) cancels the timer
• 1000ms = 1 second
• In React, always clear timers in useEffect cleanup to prevent memory leaks

🧠 Remember: always store the timer ID and clear it when done. Forgetting to clear intervals causes memory leaks and unexpected behaviour.

🎯 Try it!
Create a countdown: log 3, 2, 1, 'Go!' using setInterval. Clear the interval after 'Go!'.

⭐ What you learned
• setTimeout runs a function once after a delay
• setInterval repeats a function at regular intervals
• Always clear intervals with clearInterval() to prevent leaks

Quick Quiz

1 / 2

setTimeout runs?