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

后端 未结 9 939
终归单人心
终归单人心 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.

    0 讨论(0)
  • 2020-12-28 18:01
    var testTimeInt = 3;
    function testTime(){
    
        testTimeInt--;
    
        if(testTimeInt>0)
           setTimeOut("testTime()", 1000);
    
    }
    
    
    setTimeOut("testTime()", 1000);
    
    0 讨论(0)
  • 2020-12-28 18:04

    Like this:

    var runCount = 0;    
    function timerMethod() {
        runCount++;
        if(runCount > 3) clearInterval(timerId);
    
        //...
    }
    
    var timerId = setInterval(timerMethod, 60000);    //60,000 milliseconds
    
    0 讨论(0)
  • 2020-12-28 18:05

    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.

    0 讨论(0)
  • 2020-12-28 18:23

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

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