Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save zmts/971152f0b59488f51887ea4dbf39df87 to your computer and use it in GitHub Desktop.
Save zmts/971152f0b59488f51887ea4dbf39df87 to your computer and use it in GitHub Desktop.
Debounce with promises

Debounce with promises

// https://stackoverflow.com/questions/35228052/debounce-function-implemented-with-promises

function debounce (inner, ms = 0) {
  let timer = null
  let resolves = []

  return function (...args) {
    // Run the function after a certain amount of time
    clearTimeout(timer)
    timer = setTimeout(() => {
      // Get the result of the inner function, then apply it to the resolve function of
      // each promise that has been created since the last time the inner function was run
      const result = inner(...args)
      resolves.forEach(r => r(result))
      resolves = []
    }, ms)

    return new Promise(resolve => resolves.push(resolve))
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment