Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want a javascript function to run every minute, but max 3 times

I have a ajax javascript method that pulls data from a page etc.

I want this process to run on a timed interval, say every minute. But I don't want it to loop forever, so max out at 3 times.

What is the best way to implement this?

like image 435
mrblah Avatar asked Aug 07 '09 16:08

mrblah


People also ask

Does setTimeout have a limit?

Maximum delay value Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2,147,483,647 ms (about 24.8 days), resulting in the timeout being executed immediately.

How does the setInterval () function works in JavaScript?

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

Does setTimeout run multiple times?

The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead. Use the clearTimeout() method to prevent the function from starting.


2 Answers

Like this:

var runCount = 0;    
function timerMethod() {
    runCount++;
    if(runCount > 3) clearInterval(timerId);

    //...
}

var timerId = setInterval(timerMethod, 60000);    //60,000 milliseconds
like image 150
SLaks Avatar answered Oct 12 '22 23:10

SLaks


A closure-based solution, using setInterval() and clearInterval():

// define a generic repeater
var repeater = function(func, times, interval) {
  var ID = window.setInterval( function(times) {
    return function() {
      if (--times <= 0) window.clearInterval(ID);
      func();
    }
  }(times), interval);
};

// call the repeater with a function as the argument
repeater(function() {
  alert("stuff happens!");
}, 3, 60000);

EDIT: Another way of expressing the same, using setTimeout() instead:

var repeater = function(func, times, interval) {
  window.setTimeout( function(times) {
    return function() {
      if (--times > 0) window.setTimeout(arguments.callee, interval);
      func();
    }
  }(times), interval);
};

repeater(function() {
  alert("stuff happens!");
}, 3, 2000);

Maybe the latter is a bit easier to understand.

In the setTimeout() version you can ensure that the next iteration happens only after the previous one has finished running. You'd simply move the func() line above the setTimeout() line.

like image 29
Tomalak Avatar answered Oct 13 '22 01:10

Tomalak