JavaScript Interview Question #153

What is the difference between setTimeout() and setInterval()?

Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced

Quick Interview Answer

setTimeout schedules a callback to run once after at least the specified delay. setInterval repeatedly schedules a callback at approximately the specified interval until it is canceled.

Detailed Explanation

setTimeout schedules a callback to run once after at least the specified delay. setInterval repeatedly schedules a callback at approximately the specified interval until it is canceled.

Neither guarantees exact execution time because callbacks must wait until the JavaScript execution environment can process them. For repeated asynchronous work, recursively scheduling setTimeout after each completed operation can sometimes provide better control than setInterval.

Code Example

const timeoutId = setTimeout(() => {
    console.log("Runs once");
}, 1000);

const intervalId = setInterval(() => {
    console.log("Runs repeatedly");
}, 1000);

// Later:
clearTimeout(timeoutId);
clearInterval(intervalId);