Introduction
SetInterval() is a JavaScript function that allows you to schedule a function or expression to be executed repeatedly at specified intervals. It takes two arguments: the function to be executed and the interval at which it should be executed. The function will be called repeatedly until it is explicitly stopped using the clearInterval() method. setInterval() is commonly used to create animations, update data on a web page, and perform other tasks that require periodic execution.
Syntax
var intervalID = setInterval(function, delay, [param1, param2, ...]);
JavaScriptParameters:
- function:
- A function to be executed every
delay
milliseconds. This can be an existing function reference, an anonymous function, or a code string (though using a string is not recommended for security and performance reasons).
- A function to be executed every
- delay:
- The time, in milliseconds, the timer should wait before the specified function or code is executed.
- param1, param2, … (optional):
- Additional parameters that can be passed to the function when it is executed.
Features of setInterval() In JavaScript
- Repeated Execution: It executes the specified function repeatedly, with a fixed time delay between each execution.
- Flexibility: Developers can control the interval duration, allowing for a wide range of use cases.
- Dynamic: It enables the creation of dynamic and interactive web applications by updating content or triggering actions at regular intervals.
Why Do We Use setInterval() In JavaScript?
The primary purpose of setInterval is to create animations, update content dynamically, fetch data from servers periodically, and perform other tasks that require regular execution. It’s commonly used in web development to maintain the responsiveness and interactivity of web pages without requiring manual intervention.
Where Do We Use setInterval()?
- Animating Elements: To create animations by updating CSS properties or modifying the DOM at regular intervals.
- Fetching Data: To periodically fetch data from servers, such as fetching updates from a chat server or fetching real-time stock prices.
- Refreshing Content: To refresh content on a web page, like updating scores on a live sports website or displaying real-time weather updates.
- Polling: To poll for changes in a system, such as checking for new notifications or updates.
Examples of setInterval()
1. Simple Timer
let seconds = 0;
const intervalId = setInterval(() => {
seconds++;
console.log("Seconds elapsed: ", seconds);
}, 1000); // Interval set to 1 second
JavaScriptOutput
Seconds elapsed: 1
Seconds elapsed: 2
Seconds elapsed: 3
...
JavaScript2. Display a Text Once Every 1 Second
// program to display a text using setInterval method
function greet() {
console.log('Hello world');
}
setInterval(greet, 1000);
JavaScriptOutput
Hello world
Hello world
Hello world
Hello world
Hello world
....
JavaScriptIn the above program, the setInterval() method calls the greet() function every 1000 milliseconds(1 second).
3. Display Time Every 5 Seconds
// program to display time every 5 seconds
function showTime() {
// return new date and time
let dateTime= new Date();
// return the time
let time = dateTime.toLocaleTimeString();
console.log(time)
}
let display = setInterval(showTime, 5000);
JavaScriptOutput
"5:15:28 PM"
"5:15:33 PM"
"5:15:38 PM"
....
JavaScriptThe above program displays the current time once every 5 seconds.
Conclusion
setInterval() is a powerful tool in JavaScript for automating tasks that need to be repeated at regular intervals. Whether you’re building real-time applications, animations, or automated processes, setInterval() can help keep things running smoothly.
Frequently Asked Questions
Yes, you can stop a setInterval() using the clearInterval() method.
setInterval() repeatedly calls a function with a fixed time delay between each call, while setTimeout() only calls the function once after a specified delay.
No, it’s not always precise. The actual interval may be longer if the function takes longer to execute or if the system is under heavy load.