DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

How to Do Polling Requests to an API in JavaScript (Beginner Guide)

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
}
Enter fullscreen mode Exit fullscreen mode

🔄 How It Works

  1. Start with an API request that kicks off some process (e.g. payment).
  2. Call pollStatus() with the process ID.
  3. Your app keeps asking the server every 3 seconds.
  4. Once the server says SUCCESS or FAILED, stop polling.

🌐 Example Flow

Imagine you’re building a payment system:

  1. User clicks Pay/pay endpoint starts payment → returns transactionId.
  2. Frontend calls pollStatus(transactionId) → keeps checking /status.
  3. When /status changes from PENDING to SUCCESS, 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>
Enter fullscreen mode Exit fullscreen mode

⚠️ 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)