Search code examples
javascriptdesign-patternsobservers

How to implement server-updates-listener in client side


I have a theoretical question regarding design patterns. I would like my client to receive events from my server side, let's say when the user receives a new message in chat.

Let's assume we are running JavaScript on the client side. One way to implement this would be to send a request from the client to the server asking 'Are there any updates?' periodically. This is inefficient since we will be sending too many redundant requests when there are no updates available.

Is there a way to listen to updates from the server side only when there are such. For example implementing a receiver/listener in the client? If this can't be done with JavaScript how else would you do it?

Thank you.


Solution

  • There are a few solutions here:

    1. Have your AJAX requests run in a timed loop. While not real time, it has properties similar to a real time application.

      var requestLoop = setInterval(function(){
        //HTTP Request to update data here
      }, 60000);
      
    2. WebSockets. This is specifically what they were developed for, "With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply." Note: There are browser support issues w/ Edge/IE

    Additional: Writing WebSockets for JS

    Stackoverflow on WebSocket support: What browsers support HTML5 WebSocket API?