sync data real time without websocket in javascript

One way to sync real-time data without using websockets is to use polling. Polling involves making repeated requests to the server to check for updates. Here's an example implementation:

index.tsx
function syncData() {
  setInterval(() => {
    // Make a request to the server to fetch data
    fetch('/data')
      .then(response => response.json())
      .then(data => {
        // Update the UI with the latest data
        updateUI(data);
      })
      .catch(error => {
        console.error('Failed to fetch data:', error);
      });
  }, 1000); // Poll every 1 second
}

function updateUI(data) {
  // Update the UI with the latest data
}
450 chars
19 lines

In this implementation, the syncData() function sets up a timer that polls the server every second using setInterval(). The fetch() function is used to make a GET request to the server to fetch the latest data. Once the data is fetched, the updateUI() function is called to update the UI with the latest information.

Note that polling can create a lot of network traffic, which can be an issue in high-traffic applications. In such cases, websockets are often used as a more efficient alternative.

gistlibby LogSnag