skip to Main Content

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


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

    for (let i = 0; i < 4; i++) {
      setTimeout(() => {
        socket.emit('broadcast message', 'test client', i);
      }, i * 2000);
    }
    
    Login or Signup to reply.
  2. You were pretty close, the for loop is not necessary when using setInterval
    Also, store the setInterval into a itv variable, that way whenever you decide to stop sending automated messages you can call clearInterval(itv), not only within the setInterval function (when it matches the desired number of repeats) but also elsewhere in your code:

    let i = 0;
    const itv = setInterval(() => {
      console.log("broadcast message", "test client", ++i);   // DEMO. You, use socket.emit()
      i >= 4 && clearInterval(itv);
    }, 2000);
    
    // use
    // clearInterval(itv)
    // whenever you want to stop the interval prematurely, like on a Stop button
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search