0

I own a small messaging platform and I'm trying to make it live, so everything needs to work without any refresh. Messages are sent with Ajax and the procedure is refresh-free. I'm also trying to make sure that when Alice sends a message to Bob, Bob receives it (almost) immediately. For this reason, I'm refreshing the div containing all of the messages every second with this script:

      <script>
         $(document).ready(function() {
         var pageRefresh = 1000;
             setInterval(function() {
                 refresh();
             }, pageRefresh);
         });
         
         function refresh() {
             $("#messagesframe").load(" #messagesframe > *");
         }
      </script>

      <div id="messagesframe">
      <!-- messages displayed here! -->
      </div>

This makes sure that every second the new messages are shown. I have a doubt, however, that this may slow down the application. I am asking you, thus, whether this doubt is well-founded or if this procedure is harmless. Any help is appreciated.

Note: I'm using PHP.

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
  • it could have been better to refresh the data rather than refresh the div, but where i am having concern is if you are pulling that from the database, that will be a big issue. my advice will be, try a backend framework with events to fire up once a user has sent messages. – Emeka Okafor Feb 12 '22 at 11:48
  • Without doubt the best option for an instantaneous, bi-directional messaging platform as you wish to achieve would be to use [websockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) and perhaps the easiest might be [node.js](https://stackoverflow.com/questions/62370962/how-to-create-join-chat-room-using-ws-websocket-package-in-node-js/62867363) - plenty of [tutorials are available](https://www.google.com/search?q=node+js+websockets+tutorial) – Professor Abronsius Feb 12 '22 at 12:49

1 Answers1

1

this kind of code is not Optimal, best way for real time applications is using socket technology