Skip to content

Instantly share code, notes, and snippets.

@spion
Last active December 2, 2017 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spion/bc32c8d0cc96072b6e927174a1f57088 to your computer and use it in GitHub Desktop.
Save spion/bc32c8d0cc96072b6e927174a1f57088 to your computer and use it in GitHub Desktop.
function delay(n) { return new Promise(r => setTimeout(r, n)) }
function debounced(ms, action) {
let cancelPrevious;
let cancellation = () => new Promise((resolve, reject) => cancelPrevious = reject)
return function (...args) {
if (cancelPrevious != null) cancelPrevious()
return Promise.race([cancellation(), delay(ms)])
.then(() => action.apply(this, args))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment