From polling to long polling

一笑奈何 提交于 2019-12-13 08:50:23

问题


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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/53991213/from-polling-to-long-polling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!