-1

I have a node js program which I want to run every x number of seconds. This value will be specified by the user, and saved in mongoDB.

Now I need to ensure that my program first reads the Interval value from the dbs, and then runs the program according to this value. Also, if the user changes the interval, the program needs to reflect this too without restarting the application - is this possible?

To keep it short, this is my mongoDB value:

{ "_id" : ObjectId("398eb"), "__v" : 0, "milliseconds" : 16000 }

So I want my program to first read this value, and then run the program based on the milliseconds value.

var abc = function() {
mongoose.connect('mongodb://localhost/mas');
defaultPoll.find(function (err, interval) {
  if (err) {return console.error(err);}
  else {
    var intervalVal = JSON.stringify(interval[0].milliseconds, null, 2);
    console.log(intervalVal);
    time(intervalVal);
  }
})
mongoose.connection.close();
}

var time = function(sec){
setInterval(function() {
    // all my other functions
    console.log('hello')
}, sec, true);
}

abc();

However, the issue with this is that every 16 seconds, 'hello' is printed to the console (which is expected), but when I change the interval value in the db I need to restart the program for the changes to be picked up (which is also expected with the current code).

So, how can I achieve my program running every x number of seconds, which is specified by the user? Maybe setInterval is not the right way of thinking?

Any help or tips would be appreciated.

deeveeABC
  • 960
  • 3
  • 12
  • 34
  • Related: [Changing the interval of SetInterval while it's running](http://stackoverflow.com/questions/1280263/changing-the-interval-of-setinterval-while-its-running) – Aᴍɪʀ Nov 14 '16 at 15:36

1 Answers1

-1

You could use setTimeout instead of setInterval, that way you can specify the delay every time:

var index = 0;
var $time = $('#time');

function nextStep(time) {
    setTimeout(function() {
        index++;
        nextStep($time.val());
        console.log(index);
    }, time);
}

nextStep(500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="time" value="500"><label for="time">Time</label>
Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40