2017-09-15 125 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

为什么?这是如何解决这个问题的? –