In this article we will learn How we can setinterval and clearinterval in javascript, this is very simple process in javascript . you can leverage the setInterval()
 function, which allows you to execute a specified function repeatedly at defined intervals. it is use to create different type of animation. Or if we are not using sockets, the it is also user to fetch data from server priodically by hitting the API call with some time interval.
Understanding setInterval()
The setInterval()
 method needs two main parameters: a function to execute and the time interval in milliseconds. For instance, if you want to show a message every three seconds, you can use the following code:
setInterval(() => {
console.log("Hello");
}, 3000);
In the above code the console message will trigger every after 3sec (3000 milliseconds), but the issue in above code is it will exicute infinite times, until we stop that exicution from the code itself, and to stop time interval we use clearinterval() method. so in above code we use setInterval method in JavaScript to call a function at regular intervals.
To stop the execution of the function set by setInterval()
, you need to call clearInterval()
 with the identifier returned by setInterval()
. Here’s how you can implement this:
let animate = setInterval(() => {
console.log("This will log every second");
}, 1000);
In the above by using Function Expressions we have cached animate and on page load it will be executed and after 1sec we will be able to see console message This will log every second, but it will be a repeating step to infinity after one second, so to stop this we will use clearinterval()
How to use clearinterval()
setTimeout(() => {
clearInterval(animate);
console.log("Interval cleared");
}, 5000);
In above code we are clearing the recuring interval with clearInterval method after 5 seconds, Now lets go though one more example if we want to clear interval after certain counts
How to stop setInterval in JavaScript after a certain number of executions
<script>
let count = 0;
const maxCount = 5;
const intervalID = setInterval(() => {
count++;
console.log("This will log until count reaches 5");
if (count === maxCount) {
clearInterval(intervalID);
console.log("Stopped after 5 executions");
}
}, 1000);
</script>
The script initializes a counter variable count
to 0 and sets a maxCount
limit of 5. It uses setInterval
to execute a function every 1000 milliseconds (1 second). Within the function, count
is incremented and a message is logged to the console. When count
reaches maxCount
(5), clearInterval
is called to stop the interval timer. A final message is logged to indicate that the interval has been stopped. This ensures that the function logs a message only 5 times, then ceases execution.
Now lets go thourgh a real time web ui marketing senario , where we need to hit API call to fetch the updated data after every 10 second
how to use setInterval in JavaScript to fetch data from a server at regular intervals
<div id="data-container">Loading data...</div>
<button id="stop-button">Stop Updates</button>
In above code we have created two element data-container on which we will be able to see the updated data after every 10second, and stop-button is the element on which once clicked it will clear the time interval and stop the api calls. Now below is the javascript code to execute the api calls every after 10 sec.
// Define the API endpoint
const apiEndpoint = 'https://api.example.com/metrics';
// Variable to hold the interval ID
let intervalID;
// Function to fetch data from the API and update the UI
async function fetchData() {
try {
const response = await fetch(apiEndpoint);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
// Update the UI with the fetched data
document.getElementById('data-container').innerText = JSON.stringify(data, null, 2);
} catch (error) {
console.error('Error fetching data:', error);
document.getElementById('data-container').innerText = 'Error fetching data';
}
}
// Function to start fetching data at regular intervals
function startFetchingData() {
intervalID = setInterval(fetchData, 10000); // 10000 milliseconds = 10 seconds
// Fetch data immediately when the page loads
fetchData();
}
// Function to stop fetching data
function stopFetchingData() {
if (intervalID) {
clearInterval(intervalID);
intervalID = null;
document.getElementById('data-container').innerText = 'Updates stopped';
}
}
// Attach event listener to the stop button
document.getElementById('stop-button').addEventListener('click', stopFetchingData);
// Start fetching data when the page loads
startFetchingData();
The provided JavaScript code is designed to fetch and display data from an API at regular intervals on a webpage. It initializes an interval with setInterval to call fetchData() every 10 seconds, ensuring that the UI is updated with the latest data from the API. If the API call is successful, the data is displayed in a div with the ID data-container. If an error occurs, an error message is shown instead. The startFetchingData function triggers the data fetching process immediately upon page load. Additionally, a stopFetchingData function stops the interval and updates the UI when a button with the ID stop-button is clicked.