Alex _TNT
Alex _TNT

Reputation: 319

Having problems with setInterval on longer duration

setInterval under node.js seems not to work for delay values of 30 and more minutes. I don't know what's the problem. Reducing delay passed to setInterval in example below to just 60 seconds (by removing one * 60) makes it repeat correctly.

Can anyone point out any mistakes in my code?

I tried using https://www.npmjs.com/package/repeat but I had the same problem for 30 and 60 minutes intervals.

Here's a code sample:

function destroy() {
    console.log('Destroy');
    console.log('----------------------------------------------------------------------'); 

};

function post() {

    console.log('Post');
    console.log('----------------------------------------------------------------------'); 

    setTimeout(destroy, 1000 * 60 * 30);
};


setTimeout(destroy, null);
setTimeout(post, 1000);
setInterval(post, 1000 * 60 * 60); 

Upvotes: 3

Views: 482

Answers (1)

wolfhammer
wolfhammer

Reputation: 2661

Here's some code for a long interval. It uses timeouts of 60 seconds to check long intervals. This should work in place of setInterval. You could create a page that displays longInterval.items with their last run times.

function longInterval(fn, ms) {
  var id = longInterval.counter++;
  var now = new Date().getTime();
  var item = {ms: ms, fn: fn, last: now};
  longInterval.items[id] = item;
  return id;
}

longInterval.items = {};
longInterval.counter = 0;

longInterval.run = function() {
  var items = longInterval.items;
  var now = new Date().getTime();
  for (var k in items) {
    var item = items[k];
    if (now - item.last >= item.ms) {
      item.last = now;
      item.fn();
    }
  }

  longInterval.timeout = setTimeout(function(){
    longInterval.run();
  }, 1000 * 60);
};

longInterval.clear = function(id) {
  if (longInterval.items[id]) {
    delete longInterval.items[id]
  }
};
longInterval.run();

usage:

var myInterval = longInterval(function() {
  console.log(new Date().getTime());
}, 1000 * 60);

Upvotes: 1

Related Questions