I have a map made with OpenLayers, and I need every x time to receive updated information in the form of Geojson, to be able to position different elements in real time on the map. I am using setInterval to collect those responses that I make with the XMLHttpRequest object and my watching the execution. It does it fine, if I modify the geojson it shows the change, but is it a bad practice? Is there another way to collect information in real time?
This is my code:
window.onload = function () {
var requestURL = "data.geojson";
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.clear();
console.log(request.response);
}
}
var prueba = setInterval(function () {
request.open('GET', requestURL, true);
request.send();
}, 6000);
}
Yes, it is a good practice. There are other ways like WebWorkers, I leave you the link: https://www.w3schools.com/html/html5_webworkers.asp . If you want to collect information in real time you must use WebSocket, but it is more complicated since you must have a language in the backend with support for WebSocket (Java or NodeJS for example). WebSocket is great for your real-time purpose, websocket establishes a bidirectional client/server connection and allows the server to send information to the client without the need for a prior request from the client. I leave you a link: https://es.wikipedia.org/wiki/WebSocket. Another option is SSE (Server Sent Event), although it is also somewhat more complex and is not real time. SSE allows the server to send information to the client without a request just like WebSocket, but there is no two-way connection in which the client can send information to the server. I leave you a link: https://www.w3schools.com/html/html5_serversentevents.asp . Hope that helps, best regards.
You can always substitute
setInterval
for asetTimeout
recursive, since itsetInterval
can give certain errors sometimes (if the function doesn't need input parameters, better define it outside).The change would look like this:
In addition, in this way you make sure that the calls to the service do not start to overlap, since it
setInterval
starts counting the time for the next call from the moment it executes the code,setTimeout
it executes it once, at the end of the call you define another one exactly the same so it will always run 6 seconds (in this case) after the previous update.Hope this can help you.