2011-08-30 128 views
4

我想写一个JavaScript函数,当被调用时执行函数DoSomething()一次, 但可以触发执行该功能,直到触发停止。JavaScript的递归函数&setTimeout

我正在使用setTimeout()函数。我不确定这是从性能和记忆的角度来看最好的方法。 我也想避免全局变量,如果可能的话

<!DOCTYPE html> 
<html> 
    <script src="jquery.js"></script> 

    <script> 
    var globalCheckInventory = false; 

    $(document).ready(function(){ 
     // start checking inventory 
     globalCheckInventory = true;     
     myTimerFunction(); 
    }); 

    // check inventory at regular intervals, until condition is met in DoSomething 
    function myTimerFunction(){ 
     DoSomething(); 
     if (globalCheckInventory == true) 
     { 
      setTimeout(myTimerFunction, 5000);  
     }   
    } 

    // when condition is met stop checking inventory 
    function DoSomething() {  
     alert("got here 1 "); 
     var condition = 1; 
     var state = 2 ; 
     if (condition == state) 
     { 
      globalCheckInventory = false; 
     }   
    } 
    </script> 

回答

3

这可能是做的更简单的方法你在描述什么:

$(function() { 
    var myChecker = setInterval(function() { 
    if (breakCondition) { 
     clearInterval(myChecker); 
    } else { 
     doSomething(); 
    } 
    }, 500); 
}); 
1

另一种方式来做到这将是商店的计时器ID和使用setIntervalclearInterval

var timer = setInterval(DoSomething); 

function DoSomething() { 
    if (condition) 
     clearInterval(timer); 
} 
0

我觉得你的实现没有什么错,除了全局命名空间的污染之外。您可以使用闭合(自动执行功能)来限制你的变量是这样的范围:

(function(){ 

    var checkInventory = false, inventoryTimer; 

    function myTimerFunction() { /* ... */ } 

    function doSomething() { /* ... */ } 

    $(document).ready(function(){ 
    checkInventory = true; 
    /* save handle to timer so you can cancel or reset the timer if necessary */ 
    inventoryTimer = setTimeout(myTimerFunction, 5000); 
    }); 

})(); 
0

封装它:

function caller(delegate, persist){ 
    delegate(); 
    if(persist){ 
     var timer = setInterval(delegate, 300); 
     return { 
      kill: function(){ 
       clearInterval(timer); 
      } 
     } 
    } 
} 
var foo = function(){ 
    console.log('foo'); 
} 

var _caller = caller(foo, true); 
//to stop: _caller.kill()