繁体   English   中英

javascript - 递归函数和setTimeout

[英]javascript - recursive function & setTimeout

我正在尝试编写一个javascript函数,当被调用时执行函数DoSomething()一次,但可以被触发以重复执行函数,直到触发停止。

我正在使用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>

这可能是您描述的更简单的方法:

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

另一种方法是存储计时器ID并使用setIntervalclearInterval

var timer = setInterval(DoSomething);

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

除了污染全局命名空间之外,我认为你的实现没有任何问题。 您可以使用闭包(自执行函数)来限制变量的范围,如下所示:

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

})();

封装它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM