When working with APIs, sometimes you send a request but the response takes time. For example:
- Checking if a payment is complete (like MPESA, PayPal, Stripe).
- Waiting for a background job to finish (like file uploads or reports).
- Monitoring if a server or device is online.
In these cases, you can use polling.
🔑 What is Polling?
Polling means your application asks the server repeatedly (every few seconds) until the result changes.
Think of it like:
“Are we there yet?” → every few minutes, until the answer is yes.
🛠️ Basic Polling in JavaScript
We use setInterval()
in JavaScript to call an API repeatedly.
function pollStatus(transactionId) {
// Call the API every 3 seconds
const interval = setInterval(() => {
fetch(`/api/status?tx_id=${transactionId}`)
.then(response => response.json())
.then(data => {
console.log("Current status:", data.status);
// If status is not pending, stop polling
if (data.status !== "PENDING") {
clearInterval(interval);
alert("Final Status: " + data.status);
}
})
.catch(error => {
console.error("Error checking status:", error);
});
}, 3000); // every 3 seconds
}
🔄 How It Works
- Start with an API request that kicks off some process (e.g. payment).
- Call
pollStatus()
with the process ID. - Your app keeps asking the server every 3 seconds.
- Once the server says
SUCCESS
orFAILED
, stop polling.
🌐 Example Flow
Imagine you’re building a payment system:
- User clicks Pay →
/pay
endpoint starts payment → returnstransactionId
. - Frontend calls
pollStatus(transactionId)
→ keeps checking/status
. - When
/status
changes fromPENDING
toSUCCESS
, you update the UI.
🎯 Complete Example
<!DOCTYPE html>
<html>
<head>
<title>Polling Example</title>
</head>
<body>
<button onclick="initiatePayment()">Pay Now</button>
<p id="message"></p>
<script>
function initiatePayment() {
// Simulate calling backend payment endpoint
fetch("/api/pay")
.then(res => res.json())
.then(data => {
document.getElementById("message").innerText = "Waiting for payment confirmation...";
pollStatus(data.transactionId);
});
}
function pollStatus(transactionId) {
const interval = setInterval(() => {
fetch(`/api/status?tx_id=${transactionId}`)
.then(res => res.json())
.then(data => {
console.log("Status:", data.status);
if (data.status !== "PENDING") {
clearInterval(interval);
document.getElementById("message").innerText = "Payment " + data.status;
}
})
.catch(err => console.error("Error:", err));
}, 3000); // poll every 3s
}
</script>
</body>
</html>
⚠️ Things to Keep in Mind
- Don’t poll too frequently (2–5 seconds is common).
- Always stop polling once you get a final result.
- For large systems, consider WebSockets or Server-Sent Events for real-time updates (but polling is simpler for beginners).
✅ Summary:
Polling is a simple way to “wait” for API results in JavaScript. You use setInterval()
to call the API repeatedly until the status changes. It’s perfect for payment confirmations, job tracking, or any process where the server needs time.
Top comments (0)