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

The goal I'm trying to achieve is a client that constantly sends timer data. I need it to work endlessly. Mostly client simulator / test type.

I am having problems with setTimeout, as it is an asynchronous function called in a synchronous loop. Thus, the result is that all records from the data.json file are output at the same time.

But I am looking for:

  • output
  • wait 10s
  • output
  • 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');}
);
+3
source share
1 answer

You must pass a 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');}
);
+2
source

All Articles