如何实现函数仅在第n次调用的不同的去抖动方法


const _debounce = (n, func) => {
//code here
}
const originFun = () => {
console.log('hit')
}
const _call = () => _debounce(2, originFun)
_call() //The originFun not executes
_call() //hit
_call() //The originFun not executes
_call() //hit

我不知道如何实现它,即使在测试之后也是如此。

_debounce应该接受排序参数和originFun函数,并返回它自己的函数(或闭包(,您可以将其分配给_call。然后,您可以使用_call自己的参数(数字(来调用它。

function originFun(sort) {
console.log('hit,', sort);
}
function _debounce(sort, func) {
// Set a counter
let count = 1;
// Because closures retain the variables from the
// preceding lexical environment we can
// still use and update `count` when the function is returned
// This function (which accepts a number argument) is what's
// assigned to _call.
return function(n) {
// Call originFun with the number if the remainder of dividing
// sort by count is zero
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
if (count % sort === 0) func(n);
count++;
}
}
// _debounce returns a function that accepts a number
// argument. We assign that function to _call.
const _call = _debounce(2, originFun);
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4

这个debounce的实现应该有助于您的用例。没有全局变量,并且是用纯javascript实现的。

function _debounce(func, n){
let count = 0;
return (...args) => {
count++;
if (count % n === 0) {
count = 0;
func.apply(this, args);
}
};
}
const originFun = (sort) => {
console.log('hit,', sort)
}
const _call = _debounce((sort) => originFun(sort), 2);
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4 */
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4 */

要跟踪调用次数,可以使用全局计数器。

此外,还可以使用spread语法将参数传递给函数。这样就可以有多个参数,并且所有参数都将按顺序传递给函数。

let counter = 1;
const _debounce = (n, func, ...args) => {
if (counter === n) {
counter = 1;
func(...args);
} else {
counter += 1;
}
}
const originFun = (sort) => {
console.log('hit,', sort)
}
const _call = (sort) => _debounce(2, originFun, sort)
_call(1) //not execute
_call(2) //hit,2
_call(3) //not execute
_call(4) //hit,4

最新更新