setTimeout不能按要求工作?

我正在使用socket.io连续发送一些数据从服务器到客户端。 所以我正在使用setTimeout函数定期发送数据。 而睡眠时间不是恒定的,所以我不使用setInterval。 但setTimeout不起作用。 我正在使用服务总线从我的工作者angular色获取一些数据,这些数据将定期发送到客户端。 这是我的代码。

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); } }) } 

基本上是一个C#程序员,对JS来说很新。 请让我知道,如果我的执行setTimeout是错误的。 基本上我想要使用可变睡眠时间定期调用requestQueue方法

编辑答案:

在我看来这是一个愚蠢的问题。 我在几秒钟内使用睡眠时间,而不是毫秒。 setTimeout需要毫秒。 但我已经标记斯科特的答案,因为我认为asynchronous模块是非常有用的,可以用作setTimeout的替代品和许多其他function,如果需要的话。

它看起来像你可以受益于你的应用程序中的一些控制stream。

看看asynchronous模块。 这是直截了当的,将消除使用setTimeout的需要。

https://github.com/caolan/async