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

后端 未结 9 1029
终归单人心
终归单人心 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:01

    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.

提交回复
热议问题