2012-02-24 21 views
2

我有以下代碼的多個實例。如何將條件傳遞給運行setTimout的函數

var start_time = new Date().getTime(); 
setTimeout(function timeout(){ 
    var current_time = new Date().getTime(); 
    if(some_condition){ 
     // do stuff 
    }else if(start_time - current_time > 10000){ 
     console.error("... request is timing out."); 
    }else{ 
     setTimeout(timeout, 30); 
    } 
}, 1); 

我想它抽象成類似

globalLibrary = { 

    timeout : function(name, condition, callback, repeat){ 
     if(typeof repeat !== "number") 
      repeat = 30; 


     setTimeout(function timeout(){ 
      var current_time = new Date().getTime(); 
      if(condition){ 
       callback(); 
      }else if(start_time - current_time > 10000){ 
       console.error(name + " request is timing out."); 
      }else{ 
       setTimeout(timeout, repeat); 
      } 
     }, 1); 

    } 
} 

// .... somewhere else (not in global scope.) 
// There are vars here that are used in the condition and in the callback function. 
// They will change due to processes happening elsewhere. 
// eg ajax requests and iframe sendMessages being received. 
globalLibrary.timeout(
    "something", 
    condition, 
    function(){ 
     // do stuff. 
    }  
); 

如何做到這一點,這樣的條件隨每次迭代重新運行? 該條件可能包括多個ands和ors。

(我不使用的setInterval由於時機微妙的差異。)

回答

2

基本上,你想要的條件lazy evaluation。通過創建一個nullary函數,這很容易在支持函數式編程的語言中實現,該函數在需要時進行評估。

globalLibrary = { 
    timeout: function(name, condition, callback, repeat){ 
     if(typeof repeat !== "number") 
      repeat = 30; 

     setTimeout(function timeout(){ 
      var current_time = new Date().getTime(); 
      if (condition()) { // Note: 'condition' is called 
       callback(); 
      } else if (start_time - current_time > 10000) { 
       console.error(name + " request is timing out."); 
      } else { 
       setTimeout(timeout, repeat); 
      } 
     }, 1); 
    } 
} 

globalLibrary.timeout(
    "something", 
    function() {return condition}, 
    function(){ 
     // do stuff. 
    }  
); 
+0

謝謝,那太好了。 – SystemicPlural 2012-02-24 10:13:01