Search code examples
javascriptphpwordpressserverchat

I developed a chat with php/ajax creating a recursive function, but I'm unsure about the performance and quality of the logic used


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


Solution

  • 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.