eGluZl
eGluZl

Reputation: 13

How to implement a different debounce method that the function only called in the nth time

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

I do not know how to implement it, even after a test.

Upvotes: 1

Views: 275

Answers (3)

Andy
Andy

Reputation: 63524

_debounce should accept the sort argument, and the originFun function, and return its own function (or closure) that you can assign to _call. You can then call _call with it's own argument - the number.

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

Upvotes: 1

Junaid Hamza
Junaid Hamza

Reputation: 179

This implementation of debounce should help your use case. No global variable, and is implemented in pure 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 */

Upvotes: 0

boranseckin
boranseckin

Reputation: 345

To keep track of the number of calls you could use a global counter.

Additionally, you can pass arguments to your function using the spread syntax. That way you can have multiple arguments and all of them will be passed to the function in order.

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

Upvotes: 0

Related Questions