2017-10-17 121 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);