2016-03-21 197 views
1

clearTimeout(tt);後,tt = setTimeout(function() {停止工作。爲什麼?我有遞歸,當我手動執行getByClients時,我需要刪除setTimeout的當前隊列(如果存在)並執行新的setTimeout,而不是在clearTimeout(tt);之後,我什麼也沒有。如何刪除settimeOut的隊列工作?

var tt = undefined; 
// in default select = null, only by btn click='getByClients(1)' 
function getByClients(select) { 

    if (select == 1 || select == 2) { 
    clearTimeout(tt); // after, setTimeout is not executed 
    } 

    dashboardService.getByClients($scope.clientsMode).then(function(response) { 
     tt = setTimeout(function() { 
      getByClients(null); 
     }, refreshTime); 

    }); 
}; 

幫助,有人請(

+0

遞歸在JavaScript中通常不是一個好主意,這就是爲什麼他們創建了設置超時和循環。你也永遠不會調用最初的getByClients,所以它永遠不會開始運行,並且在第二個實例中,並且當它只有1時傳遞它兩個參數。此外,您的if語句不是雄蕊,因爲它代表了所有代碼,完全可能在清除setTimeout後清除 – Binvention

+0

@Binvention,錯過了刪除函數的參數,用於示例 – AxOn

+0

@Binvention「遞歸在JavaScript中通常不是一個好主意,這就是爲什麼他們創建設置超時和循環的原因。「這根本不是真的。這只是在編寫遞歸代碼時你必須小心。 –

回答

1

我沒有看到的遞歸代碼的需要。也許你的樣品太簡單? 如果我理解正確的話,你需要自動調用每一個X服務秒,但是你要能夠強制立即呼叫 在這種情況下,這裏是我會怎麼做:

var tt = null; 


// - Stop current timer (is started) 
function stopTimeout() 
{ 
    if(tt) 
    { 
     clearTimeout(tt); 
    tt = null; 
    } 
} 


// - Start a new Timer (and stops the previous one if any) 
function startTimeout() 
{ 
     stopTimeout(); // - to clean if already started (security) 

    tt = setTimeout(function() { 
      getByClients(); 
    }, refreshTime); 
} 


function getByClients() 
{ 
    // - Stop automatic Timer 
    stopTimeout(); 

    // - Executes Query 
    dashboardService.getByClients($scope.clientsMode).then(function(response) { 
     // - "Read response " 

    // - Restart timer 
    startTimeout(); 

     } 
    ); 
} 

// - Start automatic calls 
getByClients(); 

有在這種情況下的參數沒有必要:每次調用停止當前的超時 我認爲更好的方法可能是使用setInterval,但我想要接近您的原始代碼。

我的示例代碼在手動更新後重新啓動自動更新。我不知道這是否是你的需要?

編輯:我看你使用AngularJS,也許$超時會更好地滿足您的需求?

+0

他想要間隔通過點擊按鈕來停止 – Binvention

+0

我匆匆趕了...( – AxOn