Search code examples
node.jsazuredom-eventssettimeoutsetinterval

setTimeout not functioning as xpected?


I am using socket.io to send some data continuously from server to client. So I was using the setTimeout function to send the data periodically, and the sleep time is not constant so am not using setInterval, but setTimeout is not working. I am using service bus to get some data from my worker role which am forwarding to the client at regular intervals. Here is my code:

var sleepTime;

function requestQueue() {

sleepTime = 0;

console.log("REQUEST QUEUE STARTED");

console.log("SEND to WORKER ROLE");
// send the request to worker role
var broadcastMessage = {}
broadcastMessage.Channel = "World";
broadcastMessage.BufferSize = 10;     

sendMessage(socketToWorkerRole, broadcastMessage)

receivePeriodicRecordsQueue(workerRoleToSocket);
}

////

function receivePeriodicRecordsQueue(queue) {

serviceBusService.receiveQueueMessage(queue, function (error, receivedMessage) {
    if (!error) {
        if (receivedMessage != null) {
            var messageBody = receivedMessage.body;

            if (messageBody != null) {

                // Lots of processing and calculating sleep time
                  
                    // SET TIMEOUT
                    if (sleepTime != 0) {
                        console.log("SLEEP TIME:" + sleepTime);
                        setTimeout(function () { requestQueue(); }, sleepTime);
                    }

                      // sending data to client through socket
                    io.sockets.emit('broadcast', recordsQueue);

                }

            }
        }
    }
    else {
        console.log(error);
    }
})

}

I am basically a C# programmer, very new to JS. Please let me know if my implementation of setTimeout is wrong. Essentially I want the requestQueue method to be called periodically using a variable sleep time

EDIT ANSWER:

In my case it was a silly issue. I was using the sleep time in seconds instead of milliseconds. setTimeout requires milliseconds. I have marked Scott's as the answer because I thought the async module is pretty useful and can be used as a replacement for setTimeout and for a lot of other functionalities if needed.


Solution

  • It looks like you could benefit from some control flow in your app.

    Take a look at the async module. It is straight forward and will eliminate the need to use setTimeout.

    https://github.com/caolan/async