setInterval() is a JavaScript function used to run code repeatedly at a fixed time gap. It’s useful for tasks that need to happen continuously over time, like updates or animations.
- Executes code at regular intervals
- Keeps running until stopped manually
Syntax:
const intervalId = setInterval( func, [delay, arg1, agr2, ..., argN] );where,
- func: Function that we want to execute repeatedly after a delay of milliseconds.
- delay (optional): Number of milliseconds delay between two repeated executions of the function.
- arg1, ..., argN optional): Arguments that will be passed to the function when it is executed.
Example:
setInterval(() => {
console.log('HELLO GEEK');
}, 1000);
Here, the setInterval() method is used to repeatedly execute a function after a fixed time interval. It is useful in situations where a task needs to run continuously at regular intervals, such as updating a clock every second or fetching data periodically. A simple example demonstrating the use of setInterval() is shown below.
clearInterval() method
clearTimeout() is a JavaScript function used to cancel a timer created by setTimeout() before it gets executed. It is useful when a delayed task is no longer needed.
Syntax:
clearInterval(intervalId)where,
timeoutId: The ID returned by the setTimeout() function.
Example:
let count = 0;
const intervalId = setInterval(() => {
console.log('HELLO GEEK');
count++;
if (count === 5) {
console.log('Clearing the interval id after 5 executions');
clearInterval(intervalId);
}
}, 1000);
Here, clearInterval() is used to stop setInterval() after a limited number of executions by passing it the interval ID returned from setInterval().
Example:
let count = 0;
// The arguments passed after the
// delay (in milliseconds) will
// be received in our function
// inside the setInterval() method
const intervalId = setInterval(
(a, b) => {
console.log(`The sum of ${a} and ${b} is ${a + b}`);
count++;
if (count === 5) {
console.log("Clearing the interval id after 5 executions");
clearInterval(intervalId);
}
},
1000,
5,
10
);
Here, the arguments passed after the delay in setInterval() are received by the function and can be used as needed.
Use cases of setTimeout()
The setTimeout() method is used to execute a function after a specified delay. It is commonly used in JavaScript for scheduling tasks, creating delays, and improving user interaction in web applications.
- Displaying Notifications: Used to show alerts or messages after a specific delay.
- Creating Animations: Helps in adding timed visual effects and transitions.
- Delaying Operations: Useful for delaying API calls or code execution.
- Handling User Actions: Executes functions after a wait time following user interaction