someExpensiveOperationDebouncing

someExpensiveOperationDebouncing

我有一些输入对象。

我有一个代码,在更改它们时会执行某些操作-

for (var i=0; i<100; ++i)
  my_inputs[i].on('change', function() {
    showValue($(this).val());  // Display the value it changed to
    someExpensiveOperation();  // A common refresh for any change
  });


我想将它们全部重置为0。

for (var i=0; i<100; ++i) {
  my_inputs[i].val(0);
  my_inputs[i].change();  // Calls someExpensiveOperation 100 times!
}


重新设计代码以防止在手动重置值时调用刷新的好方法是什么?请问/递延的帮助在这里吗?

最佳答案

您可以消除对someExpensiveOperation()的呼叫:

 var someExpensiveOperationDebouncing = 0;

 function debouncedSomeExpensiveOperation() {
     if (someExpensiveOperationDebouncing) {
         return;
     }

     // wait at least 1/4 second before calling someExpensiveOperation again
     ++someExpensiveOperationDebouncing;
     setTimeout(function () {
         --someExpensiveOperationDebouncing;
     }, 250);

     someExpensiveOperation.apply(this, arguments);
 }


还可以看看lodash的_.debounce(func, [wait], [options])

07-24 16:49