[Fixed] Best practice for handling intervals for multiple clients on socket server

Issue

I am learning about Socket.io and working on creating an example where multiple clients can connect to my socket server that is broadcasting the time. However, if a client is connected, and a new one connects, it stops reading the time for the first client until they refresh the page. I was wondering if anyone would be able to explain why this is happening and what is best practice to achieve what I am looking for?

—EDIT—

I believe this has something to do with how I am setting/clearing my intervals right now.

It seems that when my clearInteral(interval) method gets hit that the connection stops for any active clients before the new one gets started.
However, I am still not entirely sure what would be the best practice to fix this.

Server:

let interval;
io.on("connection", socket => {
    console.log(socket);
    console.log("New client connected");
    if (interval) {
        clearInterval(interval);
    }

    interval = setInterval(() => getApiAndEmit(socket), 1000);
    socket.on("disconnect", () => {
        console.log("Client disconnected");
    });
});

const getApiAndEmit = async socket => {
    try {
        const d = new Date();
        const formattedDate = `${d.getMonth()}/${d.getDay()}/${d.getFullYear()}`;
        const formattedTime = `${("0"+d.getHours()).slice(-2)}:${("0"+d.getMinutes()).slice(-2)}:${("0"+d.getSeconds()).slice(-2)}`;
        socket.emit("FromAPI", `${formattedDate} ${formattedTime}`);
    } catch (error) {
        console.error(`Error: ${error.code}`);
    }
};

Client:

const endpoint = "MY_ENDPOINT";
const socket = socketIOClient(endpoint);
socket.on("FromAPI", data => this.setState({ response: data }));

Solution

yes, for each new client connection it spawns off all that’s in the socket => {} function for that specific client, so for other clients, the call to clearInterval clears the previous interval, hence why it no longer fires for other/previous clients.

The fix would be to run the interval per client, and clear it on the disconnect

io.on("connection", socket => {
    console.log("New client connected");
    
    let interval = setInterval(() => getApiAndEmit(socket), 1000);
    socket.on("disconnect", () => {
        clearInterval(interval);
        console.log("Client disconnected");
    });
});

Leave a Reply

(*) Required, Your email will not be published