How to use setInterval In Javascript
setInterval is another function in JavaScript used to execute a piece of code or a function repeatedly at a fixed interval. It allows you to execute a function repeatedly with a specified time delay between each execution.
Syntax:
setInterval(function, delay);
Example: To demonstrate printing the time at interval of 1 seconds.
function displayTime() {
console.log(new Date().toLocaleTimeString());
}
// Executes displayTime function every second
setInterval(displayTime, 1000);
Output:
Difference Between setTimeout & setInterval in JavaScript
JavaScript has both setTimeout and setInterval functions that are used for executing code after a certain delay. However, they differ in how they handle the timing of execution. Understanding their differences is crucial for effectively managing asynchronous operations in our code which is explained below:
Table of Content
- Using setTimeout
- Using setInterval
- Difference between setTimeout and setInterval