简体   繁体   中英

How to use setTimeout in Node.JS within a synchronous loop?

The goal I'm trying to achieve is a client that constantly sends out data in timed intervals. I need it to run indefinitely. Basically a simulator/test type client.

I'm having issues with setTimeout since it is an asynchronous function that is called within a synchronous loop. So the result is that all the entries from the data.json file are outputted at the same time.

But what i'm looking for is:

  • output data
  • wait 10s
  • output data
  • wait 10s
  • ...

app.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');}
);

You should pass the callback function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM