The Wayback Machine - https://web.archive.org/web/20261110145843/https://www.geeksforgeeks.org/javascript/what-is-long-polling-and-short-polling/

Long Polling and Short Polling

Last Updated : 19 Oct, 2026

Polling is a communication technique in which a client repeatedly contacts a server to check whether new data is available. It is commonly used when applications need periodic or near real-time updates without maintaining a persistent bidirectional connection such as WebSocket.

  • Short Polling: Sends requests periodically and receives an immediate response.
  • Long Polling: Sends a request that the server may keep open until new data is available or a timeout occurs.

Example: A news app refreshing every 10 seconds to fetch the latest headlines from the server.

Short Polling

Short polling is a technique where the client continuously sends requests to the server at fixed intervals. The server immediately responds—either with data if available or an empty response if not. This cycle keeps repeating, allowing the client to check for updates regularly.

  • Simple to implement using standard HTTP/AJAX requests without complex setup.
  • Can cause unnecessary requests and increase server load due to frequent polling even when no new data is available.

Example: A chat application that sends a request to the server every 5 seconds to check for new messages, even if no new messages have arrived.

420851525

Implementation Example

In this example, we took the server file as data.json which contains some data.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                         initial-scale=1.0">
    <title>Short Polling using AJAX</title>
    <style>
        h1, h3 {
            text-align: center;
            color: green;
        }

        button {
            margin-left: 34.5rem;
        }
    </style>

    <script>
        function loadInformation() {
            setInterval(function () {

                // Request
                var request = new XMLHttpRequest();
                request.open("GET", "./data.json");
                request.send();

                // Response
                request.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {

                        // Also checked status==200 to 
                        // verify its status is OK or not
                        console.log(this.responseText);
                    }
                }
            }, 1000);
        }
    </script>
</head>

<body>
    <h1>Geeks for Geeks</h1>
    <h3>Short Polling using AJAX</h3>
    <button onClick="loadInformation()">
        Click to Load
    </button>
</body>

</html>

data.json:

{
"name":"Manish",
"age":"22",
"city":"Kolkata"
}

Output:

ShortPooling

Use cases

Short polling works best in scenarios where updates are not critical and can tolerate some delay. Common use cases:

  • News feeds and blogs that refresh periodically (e.g., every few seconds or minutes)
  • Weather updates and stock market tickers with fixed refresh intervals
  • Social media feeds or dashboards that do not require immediate updates

Advantages

These highlight why short polling is easy to use but may not be efficient.

  • Simple to implement and widely supported
  • Works well for systems with less frequent updates
  • Easy to debug and maintain

Limitations

These show the limitations mainly related to performance and resource usage.

  • Sends many unnecessary requests when no data is available
  • Increases server load and network traffic
  • Not truly real-time (depends on interval delay)

Long Polling

Long polling is a technique where the client sends a request and the server holds it until new data is available instead of responding immediately. Once data is sent, the client quickly makes another request, enabling near real-time communication.

  • Reduces unnecessary empty responses and provides near real-time updates without constant repeated requests.
  • Keeps the connection open for updates, which can increase server resource usage.

Example: A messaging application where the client sends a request and waits until a new message arrives; once received, it instantly sends another request to keep listening for further messages.

420851526

Implementation Example

We will understand long polling, where we will use AJAX for understanding long polling, although, we can use normal HTTP requests as well. The steps are described below:

  • The basic creation of XMLHttpRequest to send requests is the same as in the case of short polling.
  • But here since the response is returned by the server only when it is available. So, the request can't be made at fixed intervals.
  • That's why we will send the next request only after getting the response to the previous request.

Client:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Long Polling using AJAX</title>
</head>
<body>

    <h1>GeeksforGeeks</h1>
    <h3>Long Polling using AJAX</h3>

    <button onclick="startPolling()">Start Polling</button>
    <button onclick="stopPolling()">Stop Polling</button>

    <p id="output">Waiting for updates...</p>

    <script>
        let isPolling = false;
        let activeRequest = null;

        function startPolling() {
            if (isPolling) return;

            isPolling = true;
            loadInformation();
        }

        function stopPolling() {
            isPolling = false;

            if (activeRequest) {
                activeRequest.abort();
                activeRequest = null;
            }
        }

        function loadInformation() {
            if (!isPolling) return;

            const request = new XMLHttpRequest();
            activeRequest = request;

            request.open("GET", "/updates", true);
            request.timeout = 35000;

            request.onload = function () {
                activeRequest = null;

                if (this.status === 200) {
                    const data = JSON.parse(this.responseText);

                    document.getElementById("output").textContent =
                        data.message;
                }

                // Immediately start the next long-poll request
                if (isPolling) {
                    loadInformation();
                }
            };

            request.onerror = function () {
                retryPolling();
            };

            request.ontimeout = function () {
                retryPolling();
            };

            request.send();
        }

        function retryPolling() {
            activeRequest = null;

            if (isPolling) {
                setTimeout(loadInformation, 1000);
            }
        }
    </script>

</body>
</html>

Server:

Node
const express = require("express");
const app = express();

app.use(express.static("public"));

let clients = [];

app.get("/updates", (req, res) => {
    const client = { res, timer: null };
    clients.push(client);

    // End the long-poll request after 30 seconds
    // if no new data becomes available.
    client.timer = setTimeout(() => {
        clients = clients.filter(c => c !== client);

        if (!res.headersSent) {
            res.json({ message: "No new updates" });
        }
    }, 30000);

    // Remove disconnected clients.
    res.on("close", () => {
        clearTimeout(client.timer);
        clients = clients.filter(c => c !== client);
    });
});

// Simulate new data every 10 seconds.
setInterval(() => {
    const message = {
        message: "New update at " +
                 new Date().toLocaleTimeString()
    };

    const pending = clients;
    clients = [];

    pending.forEach(client => {
        clearTimeout(client.timer);

        if (!client.res.headersSent) {
            client.res.json(message);
        }
    });
}, 10000);

app.listen(3000, () => {
    console.log("Server running on http://localhost:3000");
});

Output:

LongPooling

Use Case

Long polling is useful when applications need low-latency updates over HTTP without using a persistent bidirectional connection.

  • Chat or messaging updates where moderate real-time behavior is sufficient.
  • Notification systems such as alerts, reminders, and activity updates.
  • Job-status or task-progress monitoring.
  • Live dashboards where updates should appear quickly.
  • Applications where WebSockets or Server-Sent Events are unavailable or unsuitable.

Advantages

These make long polling more efficient for real-time-like applications.

  • Provides near real-time updates with lower latency than fixed-interval short polling.
  • Reduces repeated empty responses when updates are infrequent.
  • Works over standard HTTP infrastructure.
  • Can be useful when persistent WebSocket connections are not available.

Limitations

These drawbacks are mostly related to complexity and server resource handling.

  • Keeps HTTP requests open for longer periods.
  • Requires the server to manage many waiting connections efficiently.
  • More complex to implement than short polling.
  • Requests may time out or disconnect.
  • Requires retry and reconnection logic.

Short Polling Vs Long Polling

Both techniques are used to fetch updated data from the server, but they differ in how frequently requests are made and how the server responds.

FeatureShort PollingLong Polling
Request TimingClient sends requests at fixed intervalsClient sends a new request after the previous request completes
Server ResponseResponds immediatelyMay wait until new data is available or a timeout occurs
Empty ResponsesCommon when no new data existsReduced, but may still occur on timeout
Update LatencyDepends on polling intervalUsually lower because the server can respond when data becomes available
Network TrafficCan generate many unnecessary requestsUsually reduces unnecessary polling traffic
Connection DurationShort-lived requestsRequests may stay open for longer periods
Server Resource UsageRepeated request processingRequires management of waiting connections
ImplementationSimplerMore complex
Suitable ForPeriodic updates where some delay is acceptableNear real-time updates over HTTP
Comment