0

i'm developing a simple chat plugin, it's ready however i'm having some doubts about the performance. I'm afraid of getting heavy for the servers.

it is based on a recursive function, calling an ajax, bringing the data from the database and printing it on the screen.

window.addEventListener('load', function(){
    RenderChat()
});

const chatObjectScriptsToUrlParams = (obj) =>{
    let params = "";
    for (var key in obj) {
        if (params != "") {
            params += "&";
        }
        params += key + "=" + encodeURIComponent(obj[key]);
    }
    return params;
}

const RenderChat = () => {

    let divChat = document.getElementById('dv-chat');

    let params = {
        action: 'DvChat',
        nounce: DvChat_js.nounce,
        url: DvChat_js.dv_chat_ajax,
    };

    params = chatObjectScriptsToUrlParams(params);

    fetch(DvChat_js.url + '?' + params)
        .then((response) => {
            return response.text();
        })
        .then((html) => {
            divChat.innerHTML = html;
            console.log('HTML => ', html);
        })
        .catch( () => {

        })
        .finally(() => {
            RenderChat();
        });
}

as I said, it's a very simple way to do it, I would really like your help to know if this is really the best way, or if there are adjustments, something I can improve on this idea.

I've seen people using setInterval(); but I chose to use a recursive function to reduce the number of requests.

It's the first time I'm developing a chat, and I don't know if it's right to make so many requests the way I did, I ended up having serious doubts about the performance related to the infrastructure

  • So you just call RenderChat which triggers a fetch ajax request and when it is completed, call RenderChat again ? – Ken Lee Jun 11 '23 at 17:14
  • Exactly, that's how I did it, the function will be called at each completion, but I don't know if this way is performative, I don't know if when there are many users this would not be too much for the server, because this ajax will make constant queries in the database of data. I hope I'm not asking an absurd question but I really lack knowledge on the subject – Davi Gasparino Jun 11 '23 at 17:32
  • Take a look at [socket.io](https://socket.io/). It has a really nice transport layer for chat-style apps. No sense reinventing the flat tire if you don't have to. And if php on the server is mandatory, see this:https://stackoverflow.com/questions/6398887/using-php-with-socket-io – O. Jones Jun 11 '23 at 23:24

2 Answers2

0

This code, I believe, has two problems.

  1. It WILL overload your server and network. Mobile users will hate you, or worse, stop using your stuff.

    If you will poll your server -- hit it every so often -- you need to put some sort of time delay in between hits. Hit the server every five seconds or something, not immediately.

  2. As written you have unbounded recursion and will get a, well, stack overflow. It takes a while for this to happen in modern browsers, because they have lots of memory available.

    If this were my project I'd solve both these problems with something like this, not debugged, using setInterval().

    window.addEventListener('DOMContentLoaded', function() {
      setInterval(RenderChat, 5000)
    });   
    

    This calls your RenderChat function every five seconds (5000 milliseconds), starting when the web page is loaded. You have to get rid of the tail recursion call in your finally{} clause for this to work.

    You could also solve the unbounded recursion problem with async functions, but that's a topic for another day.

There's another problem here: it looks like the chat log -- the one you fetch on every hit -- gets longer and longer as the chat progresses. I've been on Slack chats that last for months and months. So your logs might get too long.

O. Jones
  • 103,626
  • 17
  • 118
  • 172
  • Hi O. Jones, thanks for responding. about the first problem, I think it's good for me to try something similar, yes, I'll test how it behaves and it really seems to ease the server overload problem. about the second case, in the backend I'm just delivering new messages, I ended up not putting the whole solution here, I only put the part that worries me, I really don't know very well how these things behave in real time on the servers, I'm lost so I'm at pursuit of knowledge. thank you very much help. – Davi Gasparino Jun 11 '23 at 22:59
0

For this type of application, I would recommend utilizing a websocket connection for a real-time user experience. No polling necessary. When the client receives info, it updates the server and visa-versa.

Not sure PHP is the best server-side language for this kind of app, but there is a library: Ratchet that should do what you need it to do.

TK421
  • 801
  • 5
  • 16
  • 24
  • Hi TK421, Your suggestion seemed very interesting to me, I'll try to find out more about it, maybe this is the best way. I never used websocket connection, I need to learn everything about this subject from the beginning, but I think it will solve what I want for this project – Davi Gasparino Jun 11 '23 at 23:05