Using setInterval()
to Refresh AJAX Content – A Comprehensive Guide
Introduction
In modern web applications, real-time content updates are essential to ensure users always see the most recent data without refreshing the entire page. Whether it’s for live notifications, stock market updates, live sports scores, chat applications, or dashboard statistics, using AJAX with setInterval()
can be an efficient way to achieve automatic content updates at regular intervals.
In this guide, we will explore the detailed implementation of using setInterval()
to refresh AJAX content dynamically.
Table of Contents
- Why Use
setInterval()
with AJAX? - Understanding
setInterval()
in JavaScript - Basic Example of
setInterval()
with AJAX - Fetching Live Data Using
setInterval()
- Optimizing Performance When Using
setInterval()
- Clearing
setInterval()
When Not Needed (clearInterval()
) - Handling Errors and Failures Gracefully
- Alternative Approaches – Using
setTimeout()
Instead ofsetInterval()
- Using
fetch()
withsetInterval()
Instead of jQuery AJAX - Best Practices for Implementing
setInterval()
with AJAX
1. Why Use setInterval()
with AJAX?
Using setInterval()
with AJAX allows automated data fetching at regular time intervals, ensuring users always see the latest content.
Common Use Cases:
✅ Live Sports Scores – Fetch new scores every few seconds.
✅ Stock Market Updates – Continuously update stock prices.
✅ Chat Applications – Refresh messages periodically.
✅ Real-Time Notifications – Auto-refresh notifications.
✅ Weather Updates – Display the latest weather information.
✅ IoT Device Monitoring – Continuously fetch sensor data.
✅ Live Polling Results – Refresh poll counts dynamically.
2. Understanding setInterval()
in JavaScript
The setInterval()
function repeatedly executes a function after a fixed time interval (in milliseconds).
Syntax:
setInterval(function, interval);
function
– The function to execute at every interval.interval
– Time in milliseconds between each execution.
Example:
setInterval(function() {
console.log("Hello, world!");
}, 3000); // Runs every 3 seconds
3. Basic Example of setInterval()
with AJAX
We will create a simple example that fetches data from a server every 5 seconds.
Step 1: Create the HTML Structure
<div id="data-container">Loading data...</div>
<button id="stopInterval">Stop Refresh</button>
Step 2: Write the AJAX Code with setInterval()
$(document).ready(function() {
function fetchData() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
type: "GET",
success: function(response) {
$("#data-container").html(`<p>${response.title}</p>`);
},
error: function() {
$("#data-container").html("<p>Error loading data</p>");
}
});
}
// Fetch data every 5 seconds
var intervalID = setInterval(fetchData, 5000);
// Stop refreshing when the button is clicked
$("#stopInterval").click(function() {
clearInterval(intervalID);
});
});
How It Works:
✅ The AJAX request runs every 5 seconds using setInterval()
.
✅ The data updates dynamically inside #data-container
.
✅ Clicking the “Stop Refresh” button stops the interval using clearInterval()
.
4. Fetching Live Data Using setInterval()
Let’s modify the example to fetch and update multiple data points dynamically.
Example: Auto-Updating a Table Every 10 Seconds
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody id="data-table">
<tr><td colspan="2">Loading data...</td></tr>
</tbody>
</table>
<button id="stopRefresh">Stop Refresh</button>
JavaScript Code:
$(document).ready(function() {
function loadTableData() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "GET",
success: function(response) {
var tableRows = "";
response.slice(0, 5).forEach(function(post) {
tableRows += `<tr><td>${post.id}</td><td>${post.title}</td></tr>`;
});
$("#data-table").html(tableRows);
},
error: function() {
$("#data-table").html("<tr><td colspan='2'>Error loading data</td></tr>");
}
});
}
var tableInterval = setInterval(loadTableData, 10000);
$("#stopRefresh").click(function() {
clearInterval(tableInterval);
});
});
5. Optimizing Performance When Using setInterval()
Using setInterval()
carelessly can lead to performance issues like:
❌ Multiple overlapping AJAX requests
❌ Unnecessary server load
❌ Memory leaks if intervals are not cleared
Best Practices to Optimize Performance:
✅ Set an appropriate interval time (e.g., 5-10 seconds).
✅ Ensure old AJAX requests are completed before starting new ones.
✅ Use clearInterval()
to stop updates when not needed.
6. Clearing setInterval()
When Not Needed (clearInterval()
)
To stop refreshing, use:
clearInterval(intervalVariable);
Example: Stop updates when switching tabs:
document.addEventListener("visibilitychange", function() {
if (document.hidden) {
clearInterval(tableInterval);
} else {
tableInterval = setInterval(loadTableData, 10000);
}
});
7. Handling Errors and Failures Gracefully
If the AJAX request fails, handle errors properly to prevent UI from breaking.
error: function(xhr, status, error) {
console.log("Error: ", error);
$("#data-container").html("<p>Could not load data. Retrying...</p>");
}
8. Alternative Approach – Using setTimeout()
Instead of setInterval()
A better way is to use setTimeout()
instead of setInterval()
.
function fetchData() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
type: "GET",
success: function(response) {
$("#data-container").html(`<p>${response.title}</p>`);
},
error: function() {
$("#data-container").html("<p>Error loading data</p>");
},
complete: function() {
setTimeout(fetchData, 5000);
}
});
}
fetchData(); // Start fetching data
✅ Prevents overlapping requests
✅ Waits for request completion before sending another
9. Using fetch()
with setInterval()
Instead of jQuery AJAX
function fetchData() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
document.getElementById("data-container").innerHTML = `<p>${data.title}</p>`;
})
.catch(error => console.log("Error:", error));
}
setInterval(fetchData, 5000);
10. Best Practices for Implementing setInterval()
with AJAX
✔ Use an optimal refresh interval (Too short = excessive requests).
✔ Clear intervals when switching pages/tabs.
✔ Handle errors and retries properly.
✔ Avoid duplicate requests by using setTimeout()
.
✔ Use WebSockets for real-time applications instead of AJAX polling.
Using setInterval()
with AJAX is a powerful way to auto-refresh content dynamically. However, it’s essential to handle performance issues, clear intervals when necessary, and optimize AJAX calls.
Would you like a WebSocket-based real-time alternative?