Nick
Nick

Reputation: 78

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:

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

Upvotes: 3

Views: 1724

Answers (1)

Guy Korland
Guy Korland

Reputation: 9568

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

Upvotes: 2

Related Questions