Danijel
Danijel

Reputation: 64

Node.js and socket.io initialization setInterval()

I have an event on server that is triggered when the client sends a message:

socket.on('message', function(data){
        message.push(data);
});

And now when all clients send a message, I want to wait for 3 seconds and then call a function.

I tried with Interval:

var index=0;
var timer;


socket.on('message', function(data){
    message.push(data);
    if (index==0) //only once
       timer = setInterval(call(), 3000);
    index++;
});

function call(){
     io.sockets.emit("confirmation", {status: "All messages are delivered"});
     clearInterval(timer); // Clear interval
}

The problem is that the function call() call immediately and not after 3 seconds. The second problem is that clearInterval(timer) in function call, does not work because the function call repeats.

Upvotes: 1

Views: 4518

Answers (3)

Danijel
Danijel

Reputation: 64

Thanks for all the answers. I solve the problem. The problem was that I wanted to create a setInterval() within io.on("connection", function(socket){}, but it makes for each client separately. I did not want this. Now I put before and it works:

var index=0;
var timer;
var check=false;

timer = setInterval(function(){fcall()}, 3000);

function fcall(){
   if(check)
   {
       io.sockets.emit("confirmation", {status: "All messages are delivered"});
       clearInterval(timer); // Clear interval
       timer=0;
   }
}

io.on("connection", function(socket){

   socket.on('message', function(data){
     message.push(data);
     if (index==0) //only once
       check = true;
     index++;
   });

}

Upvotes: 0

Andrew Theken
Andrew Theken

Reputation: 3480

If you only want this to occur once, you should use setTimeout instead of setInterval. This will save you from needing to clear the interval later, and makes the code more explicit that you want it to happen exactly once, 3 seconds from "now."

In addition "(...)" at the end of a function name causes it to be called immediately. You want to pass the function "call" as a parameter, not cause it to be called immediately.

I would also recommend you name the function something other than call, as this is already a name of a standard function in Javascript, and therefore can get confusing quickly. Even calling it callback would reduce confusion.

So, what you're looking for is something like this:

setTimeout(callback,3000);

in place of this

setInterval(call(), 3000);

Upvotes: 2

Sarita
Sarita

Reputation: 847

You are making a call to the function from setInterval function.

It should betimer = setInterval(call, 3000); and not timer = setInterval(call(), 3000);

Upvotes: 0

Related Questions