Reputation: 1232
I have an event in socket.io which broadcasts how many users are online (based on who is logged in) to the user.
What I think should be happening is that I ask the server to query the database once every two minutes using setInterval
, and a rowset is returned, then emitted to the client.
What is happening though, is that for each user connected to the socket, it is calling the database on the server and pushing to the client.
I'm uncertain why this is doing this - I'd understand if I was asking it to do this from the client, but as it's the server emitting the event to the client, why would it be doing this several time for each user connected?
Thanks
io.on("connection", function(socket) {
// Update online users' every two minutes
setInterval(function() {
var roomNum = 0;
var outObj = {};
model.get_online_users(function(err, rowset) {
// Loop thorugh the rowset, set the roomNum and built up out_obj to output
io.to("room_number:"+roomNum).emit("online-users", outObj);
}); // End `model callback`
}, 120000); // End `get_online_users`
}); // End `io.on("connection")`
Upvotes: 0
Views: 1282
Reputation: 814
The code in io.on("connection", function(socket) { something(); });
is called for EVERY connected user, if you put a loop in this, the loop will loop paralelly for every connected user.
The setInterval
should be outside of your io.on("connection", function(socket) { });
, and it will run once, from your node server starting to the shutdown of the server.
Example :
setInterval(function() {
var roomNum = 0;
var outObj = {};
model.get_online_users(function(err, rowset) {
io.to("room_number:"+roomNum).emit("online-users", outObj);
});
}, 120000);
Upvotes: 2