I have a basic web chat application set up using socket.io, express, node.js.
For testing purposes I am trying to get the client to send a given number of messages to another client. I have set up a for loop and tried many variations (also with while loop), but I keep ending up in an infinite loop. I have also tried console logging, which works as expected. The problem seems to be with the "socket.emit". Is there anything in particular to be aware of when using this?
My code:
for (let i = 0; i < 4; i++) {
setInterval(function(){
socket.emit("broadcast message", "test client", ++i);
}, 2000);
}
In this case I want to send the message "test client" to another client four times and then end, but it just keeps firing four and four messages in a infinite loop.
2
Answers
As pointed out in the comments, the ‘loop’ of emitted events is created by the use of setInterval.
One way to achieve what you are asking for is to use setTimeout, increasing the delay in each iteration of the
for
loop.You were pretty close, the
for
loop is not necessary when usingsetInterval
Also, store the setInterval into a
itv
variable, that way whenever you decide to stop sending automated messages you can callclearInterval(itv)
, not only within the setInterval function (when it matches the desired number of repeats) but also elsewhere in your code: