3

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');}
);
1
  • 1
    Perhaps you could use setInterval instead? Commented Feb 26, 2014 at 15:11

1 Answer 1

2

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');}
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! that was it. Damn callbacks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.