执行了一段时间的javascript / jquery函数,然后停止

时间:2016-01-20 12:23:41

标签: javascript jquery

我有2个javascript函数 - f1,f2。 我希望每2秒从f1调用f2,我需要这样做10分钟。

function f1()
{
   //call f1 in every 2 seconds- for 10 minutes
}

function f2(){
{

}

我如何在javascript / jquery中实现它,或者如何使用Settimeout,setInterval来实现上述场景。

3 个答案:

答案 0 :(得分:1)

您可以使用setTimeout()setInterval()之类的

10分钟后杀死; 10 * 60 * 1000 = 600000毫秒

var loop2s = setInterval(function(){
           f2();
    }, 2000);
// Kill after 10  minutes
setTimeout(function(){

   clearInterval(loop2s);

},600000);

答案 1 :(得分:1)

您可以使用计数器从函数本身调用f2。 快速举例:

var counter = 0;    
function f1()
{
    setTimeout(f2, 2000);
}

function f2(){
{
    counter++;
    if (counter < 59) {
        setTimeout(f2, 2000);
    }
}

答案 2 :(得分:0)

有点过头了,但是通过返回停止功能而不是使用window.clearInterval(someVar);

来解决并成为一个更好的api是一个有趣的问题

function f1(){
  // as a test this runs f2 every 400ms for 4 seconds
  var stop = interval( f2, 400, 4000 );
  // stop() is a function you can call to stop the timer asynchronously
}

function f2( elapsed ){
  console.log('called f2 at ' + elapsed + 'ms' );
}

f1();

/**
 * interval
 *
 * repeat the callback function every n milliseconds, until
 * timout or the stop() function is called
 *
 * @param {Function} cb       callback function to perform
 * @param {Number}   every    ms between interval
 * @param {Number}   timeout  timeout for interval
 *
 * @return {Function}  stop   stop function to clear the interval
 */
function interval( cb, every, timeout ){
  
  var start = Date.now(),
      timer = null;
  
  timer = window.setInterval(function(){
    var elapsed = Date.now() - start;
    if( timeout && elapsed > timeout ){
      stop();
    } else {
      cb( elapsed );
    }
  }, every);
  
  function stop(){
    window.clearInterval( timer );
  }
  
  return stop;
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>