📅  最后修改于: 2023-12-03 15:16:06.471000             🧑  作者: Mango
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.
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.
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.
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.
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.