Categories
discuss

Typescript debounce function not calling function passed as parameter

I’m trying to write a debounce function with typescript. I found an example of it in here. Code follows: export function debounce( func: (…args: Params) => any, …

I’m trying to write a debounce function with typescript.

I found an example of it in here. Code follows:

export function debounce<Params extends any[]>(
  func: (...args: Params) => any,
  timeout: number,
): (...args: Params) => void {
  let timer: NodeJS.Timeout
  return (...args: Params) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, timeout)
  }
}

Problem is:

  • Function passed as a parameter is not getting called after the specified timeout
  • I can’t use lodash or any other external library because I’m trying to avoid adding new dependencies to this project.

Thanks.

Answer

How do you use your debounce function? I prepare fiddle, you can check working solution here

function debounce<Params extends any[]>(
  func: (...args: Params) => any,
  timeout: number,
): (...args: Params) => void {
  let timer: NodeJS.Timeout
  return (...args: Params) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, timeout)
  }
}

function test(message) {
  alert(message);
}

const debouncedTest = debounce(test, 2000);

debouncedTest('message');

Well, it’s not typescript troubles

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..