Home > Software engineering >  Debounce same function with two different events
Debounce same function with two different events

Time:11-16

I want to debounce same function in two diferent scenarios, when user clicks search button and when user stops typing. So if the user types cat and in less than 1 second he clicks 3 times search icon we will only search one time, after 1 second he stops clicking search button.

I tried this:

function debounce(your_func,time=1000){...}
function search_api(){...}

$("#my_input").on("input",
  debounce(function(){search_api()})
);

$("#search_button").on("click",
  debounce(function(){search_api()})
);

This works but not exacly what we want cause it debouce it "separately", so it debounces inputs by on hand and clicks to search on the other hand.

CodePudding user response:

I found the solution but don't know why is working despite reading a lot of documentation about functions and callbacks:

function debounce(your_func,time=1000){...}
function search_api(){...}
const debounce_search = debbounce(search_api)

$("#my_input").on("input",
  debounce_search
);

$("#search_button").on("click",
  debounce_search
);

CodePudding user response:

This is because you trigger the same function so it will work as you expected.

You might think as the debounce function have a private var: timer(returned by setTimeout).

Each time you trigger this function it reset the old timer, and send a new SetTimeout, here is a simple version of debounce function.

function debounce(func, timeout = 300){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}
function saveInput(){
  console.log('Saving data');
}
const processChange = debounce(() => saveInput());

If you separate two function , which means you create two new debounced function , and they both have a private timer and setTimeout function

  • Related