📜  javascript polling - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:06.471000             🧑  作者: Mango

JavaScript Polling

Polling is a technique used in JavaScript to retrieve data from a server continuously at a set interval. In this approach, the client repeatedly requests new data from the server, whether or not there is new information available. Polling is used when there is a need to update data regularly and in real-time.

How it Works

Polling works by sending an HTTP request to the server at a set interval, usually using JavaScript's setInterval() function. The server responds with data that the client then processes as needed.

Example:
setInterval(function() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log(xhr.responseText);
    }
  };
  xhr.open("GET", "/api/data", true);
  xhr.send();
}, 5000); // Poll server every 5 seconds

In the above example, XMLHttpRequest() is used to send an HTTP GET request to the server every 5 seconds and handle the response.

Advantages and Disadvantages
Advantages
  • Polling is easy to implement and can work with most web frameworks and libraries.
  • It can be used to update data regularly and in real-time.
Disadvantages
  • Polling can consume a lot of resources, especially when there is no new information available.
  • It can lead to high network traffic and server load.
  • It may cause delays and slow down the application's performance.
Alternative: Comet

Comet is another approach used in JavaScript for real-time data updates. Unlike polling, Comet allows the server to push new data to the client whenever it is available. This approach reduces network traffic and server load and provides real-time updates without delay.

Conclusion

JavaScript polling is a technique used to retrieve data from a server continuously at a set interval. It is simple to implement but can have disadvantages such as server load and slow performance. Comet is an alternative approach that allows for real-time data updates with reduced network traffic and server load.