2016-01-20 194 views
0

我有2个javascript函数 - f1,f2。 我想每2秒钟从f1调用一次f2,我需要这样做10分钟。执行javascript/jquery函数一段时间,然后停止

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

function f2(){ 
{ 

} 

我怎么能在JavaScript/jQuery的或如何使用的setTimeout,setInterval的对于上述方案实现这一点。

回答

1

您可以使用setTimeout()一个cominbation和setInterval()

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

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

    clearInterval(loop2s); 

},600000); 
1

您可以使用计数器从函数本身调用f2。 简单的例子:

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

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

一个通过返回停机功能,而不是使用window.clearInterval(someVar);

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>

有点过头,但要解决一个有趣的问题,并成为一个更好的API