2017-10-17 120 views
0

所以我正在爲一家餐廳製作程序。當點擊桌子時,它被標記爲「支付」,並且當它再次被點擊時,您將其標記爲「離開餐廳」。我需要的是設置一個時間間隔,直到離開表格被刪除,以防萬一您錯過了表格。所以這個想法是,當你點擊一個「支付」表將其標記爲「離開」時,它會變爲灰色,持續10秒,直到它從視圖中移除,但如果再次單擊灰色表,則可以恢復該表你錯過了它。函數執行的延遲部分JavaScript和退出函數

我遇到的問題是,當我恢復「離開」表時,它在10秒內被刪除,無論如何顏色和狀態已經改變,並且如果「離開」表被恢復,我想取消以下操作。在這裏你有我正在使用的代碼。

請注意,標記爲「離開」的函數稱爲moveToFinished(orderId)。那些被標記爲「支付」的是黃色的。

function moveToFinished(orderId) { 
    var id = "btn"+orderId; 
if (document.contains(document.getElementById(id))) { 
    var btn = document.getElementById(id); 
    btn.classList.remove("yellow"); 
    btn.classList.add("grey"); 
    btn.addEventListener('click', function(){ 
    /*Here if it is clicked to restore it, I want this funcion to end right 
     after calling updateStatusToPaying(orderId);*/ 
     updateStatusToPaying(orderId); 
     return; 
    }); 

    setTimeout(function(){ 
    /*Otherwise, in 10 seconds I want to execute this, so the table is 
     removed.*/ 
      console.log("10 seconds until " + id + " is deleted.") 
      document.getElementById("tableNumbersDiv").removeChild(btn); 
    }, 10000);  
} 
} 

回答

0

您需要存儲由setTimeout返回超時ID,並用它來取消超時。

function moveToFinished(orderId) { 
    var id = "btn" + orderId; 

    if (document.contains(document.getElementById(id))) { 
     var btn = document.getElementById(id); 
     btn.classList.remove("yellow"); 
     btn.classList.add("grey"); 
     btn.addEventListener('click', function(){ 
      /*Here if it is clicked to restore it, I want this funcion to end right 
      after calling updateStatusToPaying(orderId);*/ 
      if (window.isRemoving) { 
       clearTimeout(window.isRemoving); 
      } 
      updateStatusToPaying(orderId); 
      return; 
     }); 

     window.isRemoving = setTimeout(function(){ 
      /*Otherwise, in 10 seconds I want to execute this, so the table is 
      removed.*/ 
      console.log("10 seconds until " + id + " is deleted.") 
      document.getElementById("tableNumbersDiv").removeChild(btn); 
     }, 10000); 
    } 
} 
0

您應該setTimeout的分配給一個變量,然後用戶後恢復表 - 使用clearTimeout全局函數與你作爲一個參數變量:

var timeout = setTimeout(function(){}, 10000); 
clearTimeout(timeout);