延迟部分函数执行JavaScript和退出函数

时间:2017-10-17 11:09:46

标签: javascript function timer delay exit

所以我正在为一家餐馆制作节目。单击表格时,会将其标记为“付款”,再次单击该表时,您将其标记为“离开餐厅”。我需要的是设置一个间隔直到删除离开表,以防万一你错过了表。因此,我们的想法是,当您单击“付款”表格将其标记为“离开”时,它将变为灰色10秒,直到从视图中删除,但如果再次单击灰色表,则可以将该表还原为你错过了它的情况。

我遇到的问题是,当我恢复“离开”表时,它会在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);    
 }
}

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

您应该将setTimeout分配给变量,然后在用户恢复表之后 - 使用clearTimeout全局函数将变量作为参数:

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