Skip to content

Instantly share code, notes, and snippets.

@marcog83
Created April 20, 2018 14:32
Show Gist options
  • Select an option

  • Save marcog83/6e4a3c87bc4ac8b3c5438c4481395fb5 to your computer and use it in GitHub Desktop.

Select an option

Save marcog83/6e4a3c87bc4ac8b3c5438c4481395fb5 to your computer and use it in GitHub Desktop.
debounce function that return Promise
function debouncePromise(inner, ms) {
ms = ms || 0;
var timer = null;
var resolves = [];
return function () {
var args = [].slice.call(arguments, 0);
// Run the function after a certain amount of time
clearTimeout(timer);
timer = setTimeout(function () {
// 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
var result = inner.apply(inner, args);
resolves.forEach(function (r) {
r(result);
});
resolves = [];
}, ms);
return new Promise(function (r) {
resolves.push(r);
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment