2016-01-20 186 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