How do you execute code after a certain amount of time or at regular intervals in JavaScript?
💡 Model Answer
JavaScript provides two global functions for delayed or repeated execution: setTimeout and setInterval.
setTimeout(callback, delay) schedules callback to run once after delay milliseconds. It returns a timer ID that can be passed to clearTimeout to cancel the execution.
setInterval(callback, interval) schedules callback to run repeatedly every interval milliseconds. It returns a timer ID that can be passed to clearInterval to stop the repetition.
Both functions accept an optional list of arguments to pass to the callback. Because they rely on the event loop, the callback will execute only after the current call stack is empty and the specified delay has elapsed. Common pitfalls include forgetting to clear timers, leading to memory leaks, or using setInterval for long‑running tasks, which can cause overlapping executions. For most use cases, setTimeout (possibly recursively) is safer than setInterval.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500