2014-02-26 36 views
3

我試圖實現的目標是一個不間斷地發送數據的客戶端。我需要它無限期地運行。基本上是模擬器/測試類型的客戶端。如何在同步循環內的Node.JS中使用setTimeout?

我遇到了setTimeout的問題,因爲它是在同步循環內調用的異步函數。所以結果是data.json文件中的所有條目都是同時輸出的。

但我正在尋找的是:

  • 輸出數據
  • 等待10秒
  • 輸出數據
  • 等待10秒
  • ...

應用。 js:

var async = require('async'); 

var jsonfile = require('./data.json'); 

function sendDataAndWait (data) { 
    setTimeout(function() { 
     console.log(data); 
     //other code 
    }, 10000); 
} 

// I want this to run indefinitely, hence the async.whilst 
async.whilst(
    function() { return true; }, 
    function (callback) { 
     async.eachSeries(jsonfile.data, function (item, callback) { 
      sendDataAndWait(item); 
      callback(); 
     }), function(err) {}; 
     setTimeout(callback, 30000); 
    }, 
    function(err) {console.log('execution finished');} 
); 
+1

也許你可以使用'setInterval'呢? – user2428118

回答

2

你應該通過回調函數:

function sendDataAndWait (data, callback) { 
    setTimeout(function() { 
     console.log(data); 
     callback(); 
     //other code 
    }, 10000); 
} 

// I want this to run indefinitely, hence the async.whilst 
async.whilst(
    function() { return true; }, 
    function (callback) { 
     async.eachSeries(jsonfile.data, function (item, callback) { 
      sendDataAndWait(item, callback); 
     }), function(err) {}; 
     // setTimeout(callback, 30000); 
    }, 
    function(err) {console.log('execution finished');} 
); 
+1

謝謝!就是這樣。該死的回調! :) – Nick

+0

謝謝!是的,回調。 – wazhao