简体   繁体   中英

From polling to long polling

So I have a script that uses basic polling to show the total amount of records in the database in real time

so nothing complicated so can any one give me an example of my code in a long polling structure. The reason why I ask this question because all the articles on google

search gives me examples in jQuery I cant seem to find a plain JavaScript example that makes sense in my situation. This is a .gif screenshot of my code in action so you guys know what I mean in detail.

.gif 示例

This is my basic polling example code that I need to convert or change into long polling.

index.php

<style>
    #label{
    margin: 0;
    color: red;
    font-weight: bold;
    }
    </style>

    <script>
    document.addEventListener('DOMContentLoaded',function(){

    /**********************************************************************
    Check for a new record amount in the data base
    **********************************************************************/

    function checkForNewRecords(){

    var xhr= new XMLHttpRequest();

    xhr.onreadystatechange= function(){

        if(xhr.readyState == 4){
        document.querySelector('#output').innerHTML= xhr.responseText;

        }
      }

    xhr.open('POST','check-for-new-records.php');
    xhr.send();  

    }

    setInterval(function(){checkForNewRecords()},1000);

    });
    </script>

    <p id='label'>Total records in the database in real time in basic polling</p>

    <div id='output'></div>

check-for-new-records.php

<?php

    $db_servername= 'localhost';
    $db_username='jd';
    $db_password= '1234';
    $db_name= 'test';

    $db_connect= new mysqli($db_servername,$db_username,$db_password,$db_name);

    $db_query= "SELECT COUNT(id) AS id FROM example";

    $db_result= $db_connect->query($db_query);
    $db_row= $db_result->fetch_object();

    $total_records= $db_row->id;

    ?>

    <style>
    #total-records{
    margin-top: 0;
    }
    </style>

    <p id='total-records'><?php echo $total_records; ?></p>

So how would you guys convert this into long polling and please don't suggest other methods or don't provide an answer that is not helpful i'm only interested in what i'm asking for and i'm pretty sure others are also interested in a plain JavaScript version as well and the reason why I say this is because I

been asking about this topic online for a long time and nobody seems interested in answering this or perhaps they think its too hard to answer this if so why is there so many jQuery examples about this topic and not based on plain JavaScript and not everyone likes to use libraries. I'm just saying I been unsatisfied about the unhelpful answers I been getting from this topic that is based on plain JavaScript, just a heads up.

You should never use setInterval use setTimeout instead.

If you use setTimeout then basic difference for polling and long polling is only where the delay happens. For polling the server will respond immediatly (even if no change happened) and the client will wait n seconds to send the next request. For long polling the server will wait with the respond until new data is available (or a timeout occurs) and the client will immediately send a new request when it gets a response.

There is absolutely no different in implementing it with XMLHttpRequest , fetch or jQuery , the only difference client side is the delay for the next request.

Polling:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 1000); // polling has the delay on the client
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

Long-Polling:

function checkForNewRecords() {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (xhr.readyState == 4) {
      document.querySelector('#output').innerHTML = xhr.responseText;

      setTimeout(checkForNewRecords, 0);
      // long-polling has the delay on the server 
      // the client initiates a new request immediatly after receiving the response.
    }
  }

  xhr.open('POST', 'check-for-new-records.php');
  xhr.send();

}

checkForNewRecords()

On the server side, on the other hand, you usually have to change a couple of things to make long polling work efficiently.

The important differences between polling and long polling that target optimizations, in how to tell the server when to send update informations, but thats completely independent form the method you use to request the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM