mrblah
mrblah

Reputation: 103597

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?

Upvotes: 18

Views: 27725

Answers (9)

Jose G Varanam
Jose G Varanam

Reputation: 767

you can do with setInterval

var count = 0;

var interval = setInterval(yourFunction(), 1000);

function yourFunction (){

  clearInterval(interval);  
  if(count < 3){

    count ++;
    interval = setInterval(yourFunction(), 1000);
  }

// your code


}

Upvotes: 4

lepe
lepe

Reputation: 25210

To extend Tomalak function:

If you want to know how many cycles are left:

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

and use:

repeater(function(left){
    //... (do you stuff here) ...
    if(left == 0) {
        alert("I'm done");
    }
}, 3, 60000);

Upvotes: 3

Eli Grey
Eli Grey

Reputation: 35895

This anonymous function (it doesn't introduce any new globals) will do what you need. All you have to do is replace yourFunction with your function.

(function(fn, interval, maxIterations) {
    var iterations = 0,
    id = setInterval(function() {
        if (++iterations > maxIterations)
            return clearInterval(id);

        fn();
    }, interval);
})(yourFunction, 60000, 3);

Upvotes: 4

Tomalak
Tomalak

Reputation: 338316

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.

Upvotes: 12

Peter Bailey
Peter Bailey

Reputation: 105908

A reusable approach

function setMaxExeuctionInterval( callback, delay, maxExecutions )
{
  var intervalCallback = function()
  {
    var self = intervalCallback;
    if ( 'undefined' == typeof self.executedIntervals )
    {
      self.executedIntervals = 1;
    }
    if ( self.executedIntervals == maxExecutions )
    {
      clearInterval( self.interval )
    }
    self.executedIntervals += 1;
    callback();
  };
  intervalCallback.interval = setInterval( intervalCallback, delay );
}

// console.log requires Firebug
setMaxExeuctionInterval( function(){ console.log( 'hi' );}, 700, 3 );
setMaxExeuctionInterval( function(){ console.log( 'bye' );}, 200, 8 );

Upvotes: 4

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53607

Use setInterval, be sure to get a reference.

var X=setInterval(....);

Also, have a global counter

var c=0;

Inside the function called by the setIntervale do:

c++;
if(c>3) window.clearInterval(X);

Upvotes: 2

andres descalzo
andres descalzo

Reputation: 14967

var testTimeInt = 3;
function testTime(){

    testTimeInt--;

    if(testTimeInt>0)
       setTimeOut("testTime()", 1000);

}


setTimeOut("testTime()", 1000);

Upvotes: 0

SLaks
SLaks

Reputation: 887767

Like this:

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

    //...
}

var timerId = setInterval(timerMethod, 60000);    //60,000 milliseconds

Upvotes: 43

Nosredna
Nosredna

Reputation: 86276

You can use setInterval() and then inside the called function keep a count of how many times you've run the function and then clearInterval().

Or you can use setTimeout() and then inside the called function call setTimeout() again until you've done it 3 times.

Upvotes: 1

Related Questions