想要每分钟运行一次javascript函数,但最多3次

我有一个ajax javascript方法从页面中提取数据等。

我希望这个过程以定时间隔运行,比如说每分钟。 但我不希望它永远循环,所以最多3次。

实现这个的最佳方法是什么?

像这样:

 var runCount = 0; function timerMethod() { runCount++; if(runCount > 3) clearInterval(timerId); //... } var timerId = setInterval(timerMethod, 60000); //60,000 milliseconds 

基于闭包的解决方案,使用setInterval()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); 

编辑:另一种表达相同的方式,使用setTimeout()代替:

 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); 

也许后者更容易理解。

setTimeout()版本中,您可以确保下一次迭代仅在前一次迭代完成才会发生。 您只需将func()行移动到setTimeout()上方即可

一种可重复使用的方法

 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 ); 

你可以用setInterval做

 var count = 0; var interval = setInterval(yourFunction(), 1000); function yourFunction (){ clearInterval(interval); if(count < 3){ count ++; interval = setInterval(yourFunction(), 1000); } // your code } 

这个匿名函数(它不会引入任何新的全局变量)将满足您的需求。 您所要做的就是用您的函数替换您的函数。

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

扩展Tomalakfunction:

如果你想知道剩下多少个周期:

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

并使用:

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

使用setInterval,一定要获得参考。

 var X=setInterval(....); 

还有一个全球反击

 var c=0; 

在setIntervale调用的函数内部执行:

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

你可以使用setInterval()然后在被调用的函数内部保持你运行函数的次数,然后是clearInterval()。

或者你可以使用setTimeout()然后在被调用的函数内再次调用setTimeout(),直到你完成它3次。

 var testTimeInt = 3; function testTime(){ testTimeInt--; if(testTimeInt>0) setTimeOut("testTime()", 1000); } setTimeOut("testTime()", 1000);