2017-09-15 47 views
-2

我有一個使用JavaScript的文本框提交功能。當腳本觸發時,它會檢查Kendo網格中的特定文章,並在其數量上添加+1,並在編輯模式下打開相應的單元格。我想實現的是,在每次提交時,啓動grid.editCell()的計時器將重置其計時器。JavaScript clearTimeout沒有正確觸發

目前,活動正常啓動。但是,定時器不會被重置,但clearTimeout()確實有效,如果我只是簡單地啓動定時器,然後立即清除它。

的JavaScript:

$('#txtBarcode').submit(function (e) {   
    var grid = $("#PickListDetailGrid").data("kendoGrid"); 
    var dataSource = $("#PickListDetailGrid").data("kendoGrid").dataSource; 
    var allData = grid.dataSource.data(); 
    var code = this.value; 
    var notification = $("#notification").data("kendoNotification"); 
    var timer = null; 
    clearTimeout(timer); 

    $.each(allData, function (index, item) { 
     if (item.ArticleID == code) { 
      clearTimeout(timer); 
      timer = null; 
      if (item.Quantity > item.PickedQuantity && item.PickedQuantity.toString().length < 4) { 

       var edit = function() { 
        if (item.PickedQuantity != item.Quantity && timer != null) { 
         grid.select("tr:eq(" + (index) + ")"); 
         grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")"); 
        } else { 
         //do nothing 
        }       
       } 

       item.PickedQuantity++; 
       item.dirty = true; 
       dataSource.sync(); 

       if (item.PickedQuantity != item.Quantity) { 
        console.log("tik tok");       
        if (timer) { 
         clearTimeout(timer); //cancel the previous timer. 
         timer = null; 
        } 
        timer = setTimeout(edit, 3000); 
       } else { 
        clearTimeout(timer); 
        timer = null; 
       } 
       document.getElementById("txtBarcode").value = ""; 

      } else {  
       if (item.PickedQuantity.toString().length > 4) { 

        notification.hide(); 
        notification.show({ 
         message: "Added item" 
        }, "upload-success"); 
       } else { 
        notification.hide(); 
        notification.show({ 
         title: "Quantity Error", 
         message: "You already picked this item to the maximum" 
        }, "error"); 
        document.getElementById("txtBarcode").value = ""; 
        grid.select("tr:eq(" + (index) + ")"); 
        grid.editCell("tr:eq(" + (index + 1) + ") td:eq(" + (5) + ")"); 
        $('.focus :input').focus(); 
       } 
      } 
     } 
    }) 
}) 

回答

0

的問題是var timer = null;必須是提交功能以外的分配新setTimeout()它前,適當地清除,並設置爲null。

0

你可以嘗試這樣的延時功能。延遲功能應該在每個功能之外。

var delay = (function() { 
    var timer = 0; 
    return function(callback, ms) { 
     clearTimeout(timer); 
     timer = setTimeout(callback, ms); 
    }; 
})(); 

delay(function() { 
    //do something 
}, 3000); 
+0

爲什麼?這是如何解決這個問題的? –