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

后端 未结 9 940
终归单人心
终归单人心 2020-12-28 17:43

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 forev

相关标签:
9条回答
  • 2020-12-28 18:26

    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 );
    
    0 讨论(0)
  • 2020-12-28 18:27

    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);
    
    0 讨论(0)
  • 2020-12-28 18:28

    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);
    
    0 讨论(0)
提交回复
热议问题