JavaScript provides built-in functions to execute code after a specified time delay or at regular intervals.
1. setTimeout(callbackFunction, delayInMilliseconds, arg1, arg2, ...)
:
Executes callbackFunction
once after the delayInMilliseconds
has passed. Any additional arguments (arg1
, arg2
, etc.) are passed to the callback function.
setTimeout
returns a timer ID, which can be used with clearTimeout()
to cancel the timer before it executes.
function greetLater() { console.log("Hello after 2 seconds!"); } let timerId = setTimeout(greetLater, 2000); // 2000 milliseconds = 2 seconds // To cancel: // clearTimeout(timerId); // Using an anonymous function and arguments: setTimeout(function(name) { console.log("Hello, " + name + ", after 3 seconds!"); }, 3000, "Developer");
2. setInterval(callbackFunction, intervalInMilliseconds, arg1, arg2, ...)
:
Repeatedly executes callbackFunction
with a fixed time intervalInMilliseconds
between each call.
setInterval
also returns a timer ID, which can be used with clearInterval()
to stop the repeated execution.
let count = 0; function showCount() { count++; console.log("Count: " + count); if (count >= 5) { clearInterval(intervalId); // Stop after 5 executions console.log("Interval stopped."); } } let intervalId = setInterval(showCount, 1000); // Execute every 1 second
Both setTimeout
and setInterval
are asynchronous, meaning they don't block the execution of other JavaScript code. The JavaScript engine schedules the callback to run after the delay/interval, but continues processing other tasks in the meantime.