Open In App

What is Long Polling and Short Polling ?

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will know about the Polling concept, along with knowing the different types of Polling available, with an understanding of the basic differences between them & the related code examples.

Polling simply means checking for new data over a fixed interval of time by making API calls at regular intervals to the server. It is used to get real-time updates in applications. There are many applications that need real-time data and polling is a life savior for those applications.

Different types of Polling:

  • Short Polling: In a short polling client requests data from the server and the server will return the response if it is available and if it is not available then it returns an empty response. This process will be repeated at regular intervals.

We will understand short polling with the help of an example, where will use AJAX to understand Short Polling, although, we can also use normal HTTP requests. 

Steps for short Polling using AJAX are given below:

  • create a new XMLHttpRequest.
  • Use the open() method of XMLHttpRequest to specify the request.
  • Use send() method of XMLHttpRequest to send a request to the server.
  • Use the “onreadystatechange” property of XMLHttpRequest to define a function that will help us to use our response at any place.
  • Use responseText inside that function to show your data anywhere on the webpage.
  • Place this entire request and response in setInterval by specifying an interval.
  • Then place that setInterval inside a function that will be called on the button click.

Example 1: 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:

Short Polling

Although, there are a few problems with short polling, i.e., the frequency of polling can cause an unacceptable burden on the network, the server, or both, when the acceptable latency is low, in general.

Long Polling: In Short polling, there was a problem that if the response is not available then the server returns an empty response.

So, In long polling, this problem got solved. Here, in long polling, the client sends a request to the server and if the response is not available then the server will hold the request till the response gets available, & after the availability of the response, the server will send the response back. After getting a response, again the request will be made either immediately or after some period of time and this process will repeat again and again. In simple words, the client will always be in the live connection to the server.

Example 2: In this 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.

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>
    <style>
        h1, h3 {
            text-align: center;
            color: green;
        }
 
        button {
            margin-left: 34.5rem;
        }
    </style>
 
    <script>
        function loadInformation() {
 
            // 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);
                    loadInformation();
                }
            }
        }
    </script>
</head>
 
<body>
    <h1>Geeks for Geeks</h1>
    <h3>Long Polling using AJAX</h3>
    <button onClick="loadInformation()">
        Click to Load
    </button>
</body>
 
</html>


data.json:

{
    "name":"Mridul",
    "age":"24",
    "city":"Banglore"
}

Output:

 

Real-World Polling Applications: Polling has different Real-world Applications. Some of them are described below:

  • Taxi Service Provider: When any user books a taxi from the taxi service provider’s application then, in that case, he/she needs to check the location of the driver every second to get an idea that how far the driver is from its pickup point.

In that case, data on the location change rapidly so we need polling to get the correct location every time.

  • Train Tracking When any user wants the current location of any train then he/she uses the Train tracking application. Since the location of the train changes every moment. So, in this case, also there is a need for polling to get the updated location of the train at any time whenever a user searches.

Difference between Short Polling and Long Polling:

Short Polling

Long Polling

It is based on Timer. So, it is used for those applications that need to update data at a fixed interval of time

It is based on getting the response. So, It is used for those applications that don’t want empty responses.

Here, an empty response can be sent if a response is not available.

Here empty response can never be sent.

It is less preferred.

It is more preferred, in comparison to Short Polling.

It creates lots of traffic.

It also creates traffic but less than short polling.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads