debounce获取前一个函数的调用参数

lodash.debounce get previous function's call arguments

本文关键字:函数 一个 调用 参数 获取 debounce      更新时间:2023-09-26

当_d .debounce被多次调用时,它只应用于最后一次调用的参数。

var f = _.debounce(function(a) {
    console.log(a);
})
f(12)
f(1223)
f(5)
f(42)
//output -----> 42

是否有一种方法可以获得前一个函数的调用参数?

,

 var f = _.customDebounce(function(a) {
    console.log(a);
})
f(12)
f(1223)
f(5)
f(42)
//output -----> [12, 1223, 5, 42]

我最终自己实现了这个函数,扩展了lodash:

_.mixin({
  debounceArgs: function(fn, options) {
      var __dbArgs = []
      var __dbFn = _.debounce(function() {
          fn.call(undefined, __dbArgs);
          __dbArgs = []
      }, options);
      return function() {
          __dbArgs.push(_.values(arguments));
          __dbFn();
      }
  },
  throttleArgs: function(fn, options) {
      var _thArgs = []
      var _thFn = _.throttle(function() {
          fn.call(undefined, _thArgs);
          _thArgs = []
      }, options);
      return function() {
          _thArgs.push(_.values(arguments));
          _thFn();
      }
  },
})

用法:

_.debounceArgs(function(a) {
   console.log(a);
})

下面是跟踪其参数的简单解析。它不会模仿_.debounce

的最后一个参数

function customDebounce(func, wait) {
  var args = [];
  var timeoutId;
  return function() {
    // User formal parameters to make sure we add a slot even if a param
    // is not passed in
    if (func.length) {
      for (var i = 0; i < func.length; i++) {
        if (!args[i]) {
          args[i] = [];
        }
        args[i].push(arguments[i]);
      }
    }
    // No formal parameters, just track the whole argument list 
    else {
      args.push(_.toArray(arguments));
    }
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
      func.apply(this, args);
      args = [];
    }, wait);
  }
}
// For named arguments, each of the arguments becomes an array that tells
// you how many times it was called
var f = customDebounce(function(a, b, c) {
  console.log('Debounced func called',
    a.length,
    'times', JSON.stringify({
      a: a,
      b: b,
      c: c
    }));
});
f(1, 3);
f(2, 3, 5);
f(3);
f(4, 2, 3);
// Debounced func called 4 times 
// {"a":[1,2,3,4],"b":[3,3,null,2],"c":[null,5,null,3]}
// Can also be used with unnamed arguments, parameters are passed a little 
// differently, each element in `arguments` is the array of arguments for 
// that call, the latest one being at the end of the array
var g = customDebounce(function() {
  console.log('Debounced no params func called ',
    arguments.length,
    'times',
    JSON.stringify({
      args: _.toArray(arguments)
    }));
});
g(1, 3);
g(2, 3, 5);
g(3);
g(4, 2, 3);
// Debounced no params func called  4 times
// {"args":[[1,3],[2,3,5],[3],[4,2,3]]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>