What is setTimeout?
`setTimeout` is a asynchronous, built-in JavaScript function that allows you to execute a function after a specified delay in milliseconds. It's commonly used when you want to delay the execution of some code, such as in animations, asynchronous operations, or time-based events. And setTimeout returns a unique timer ID
The syntax for setTimeout is:setTimeout(function, delay, arg1, arg2, ...)
- function: The function to be executed after the delay.
- delay: The time (in milliseconds) that the function will wait before being executed. 1000 milliseconds equals 1 second.
- arg1, arg2, ...: Optional additional arguments that will be passed to the function when it's executed.
Here's an example of using setTimeout to delay a function call by 3 seconds and pass multiple arguments to the function:
function greet(name, greeting) {
console.log(`${greeting}, ${name}!`);
}
setTimeout(greet, 3000, "Prakash", "Hello"); // This will log "Hello, Prakash!" after 3 seconds
setTimeout(greet(), 3000, "Prakash", "Hello") // This will not work
setTimeout(()=>{
console.log("Hi)
},2000) // This will log "Hi" after 2 seconds, no arguments
In this example:
- The
greetfunction takes two parameters:nameandgreeting. - We pass
greetas the first argument tosetTimeout, followed by a delay of 3000 milliseconds (3 seconds), and then provide the arguments"Prakash"and"Hello". - After 3 seconds, the
greetfunction is called with those arguments, and the output will be:Hello, Prakash! setTimeouttake function reference, calling function won't work.
As mentioned earlier, setTimeout returns a unique timer ID, which can be used with clearTimeout to cancel the timeout if needed:
const timerId = setTimeout(() => {
console.log("This won't execute if cancelled");
}, 3000);
// To cancel the timeout before it runs:
clearTimeout(timerId);In this example, clearTimeout(timerId) will prevent the timeout function from executing if the timeout is canceled before the delay ends.
What is `setInterval`?
`setInterval` is a asynchronous, built-in JavaScript function that is similar to `setTimeout`, but instead of executing the function once after a delay, it executes the function repeatedly at fixed intervals (e.g., every 3 seconds). This makes it ideal for tasks that need to happen periodically, like polling a server, updating a UI, or running background tasks.
The syntax for setInterval is:setInterval(function, interval, arg1, arg2, ...)
- function: The function that will be executed repeatedly.
- interval: The time (in milliseconds) between each execution of the function. 1000 milliseconds equals 1 second.
- arg1, arg2, ...: Optional additional arguments that will be passed to the function each time it runs.
Here's an example of using setInterval to log a message every 2 seconds:
setInterval(() => {
console.log("This prints every 2 seconds");
}, 2000); // 2000ms = 2 secondsIn this example:
- The anonymous function
() => { console.log("This prints every 2 seconds"); }will be executed every 2 seconds (2000 milliseconds). - The console log will print
"This prints every 2 seconds"repeatedly every 2 seconds.
Just like setTimeout, setInterval returns a unique timer ID. This ID can be used with clearInterval to stop the repeated executions:
const intervalId = setInterval(() => {
console.log("This will be stopped after 5 seconds");
}, 1000);
// To stop the interval after 5 seconds:
setTimeout(() => {
clearInterval(intervalId);
console.log("Interval cleared");
}, 5000);In the above example:
- We first set an interval that logs a message every second.
- After 5 seconds, we use
setTimeoutto callclearInterval(intervalId), which stops the repeated execution of the function. - The output will include the repeated logs for 5 seconds and then log "Interval cleared" after the interval is stopped.
It's important to note that setInterval will continue to run until it's explicitly cleared using clearInterval. This makes it crucial to manage intervals properly to avoid potential performance issues in long-running applications.
`setTimeout` and `setInterval` with 0 Delay and with No Time
setTimeout
Sometimes, you might want to defer the execution of a function until the current stack of synchronous code finishes executing, but without specifying any actual delay. In this case, you can use setTimeout with a delay of 0 or no delay at all (which defaults to 0).
console.log("Start");
// Using setTimeout with 0ms delay
setTimeout(() => {
console.log("Executed (with 0ms delay).");
}, 0);
// Using setTimeout without specifying a delay (defaults to 0ms)
setTimeout(() => {
console.log("Executed (with no time specified).");
});
console.log("End");In this example:
- "Start" is logged first.
- Both
setTimeoutfunctions (with0ms delay and without a delay) are placed in the event queue. - "End" is logged next, as it is part of the synchronous code.
- Finally, after all the synchronous code finishes, both callbacks are executed, logging their respective messages.
Whether you use setTimeout(callback, 0) or setTimeout(callback), the behavior is the same: the function will be executed after the current execution context finishes, without any actual delay between the function calls.
setInterval(() => {
console.log("Executed (with 0ms delay)."); // This will log the message every 0ms delay
}, 0); // 0ms delay: The function will be executed repeatedly after 0 milliseconds
setInterval(() => {
console.log("Executed (with 0ms delay).");
});
//default 0ms delay: The function will be executed repeatedly after 0 milliseconds
Key Differences Between `setTimeout` and `setInterval`
| Feature | setTimeout | setInterval |
|---|---|---|
| Purpose | Executes once after a delay | Executes repeatedly at specified intervals |
| Execution Frequency | One-time execution | Repeated execution |
| Delay | Delay is provided in milliseconds | Interval is provided in milliseconds |
| Cancellation | Can be cancelled using `clearTimeout` | Can be cancelled using `clearInterval` |
Important Notes
- `setTimeout` and `setInterval` do not block the main thread, meaning they run asynchronously.
- Both functions can be canceled using `clearTimeout` and `clearInterval` respectively.
- These functions are not part of the JavaScript core but are provided by the browser's environment.
Key Takeaways:
- Use `setTimeout` for delayed execution of a function once.
- Use `setInterval` for periodic execution of a function at fixed intervals.