Skip to content

How to wait for new information from a node.js server

so i am making a small chat lobby project. But im having issues with getting the messages people are sending to the server, back to the clients to show them on the site. It kind of worked using a loop like this:

//Client side
setInterval(() => {
    let ajax = new XMLHttpRequest()
    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            serverMessages = JSON.parse(ajax.responseText);
            if (serverMessages.join("") !== clientmessages.join("")) {
                let newMessages = arrDiff(clientmessages, serverMessages)
                clientmessages = serverMessages
                newMessages.forEach(msg => {
                    chatText.innerHTML += `<ul>${msg.name}: ${msg.message}</ul>`
                })
            }
        }
    };
    ajax.open("GET", `/message?code=${getUrlParam("code")}`, true)
    ajax.send()
}, 100)

//Server side
app.get("/message", (req, res) => {
    res.send(lobbies.get(req.query.code).messages)
})

However this is obviosly really bad, and if you started spamming, or too many clients joined, it overloaded the server with requests, causing all kinds of bugs.

So im asking, how can i do this better? Or is there a way to wait untill the server gets new information?

Answer

Try using socket.io instead of ajax/https calls, I think it will be more efficient.