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

后端 未结 9 1000
终归单人心
终归单人心 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 );
    

提交回复
热议问题