Skip to content

Instantly share code, notes, and snippets.

@modernserf
Created January 30, 2015 22:00
Show Gist options
  • Save modernserf/e09ba3aa9e5788803f97 to your computer and use it in GitHub Desktop.
Save modernserf/e09ba3aa9e5788803f97 to your computer and use it in GitHub Desktop.
Debounce Promise
function debouncePromise (func, wait){
var later, boundFn, promise, min = 10;
var bind = function (fn, ctx, args){
boundFn = function (done){
done(fn.apply(ctx, args));
};
};
var reset = function (){ promise = null; };
var resolve = function (){
window.setTimeout(reset, min);
return promise;
};
var sleepLoop = function (done){
var diff = later - Date.now();
if (diff > min){
window.setTimeout(sleepLoop, diff, done);
} else {
promise = promise || new Promise(boundFn);
done();
}
};
return function (/* arguments */){
later = Date.now() + wait;
bind(func, this, arguments);
return new Promise(sleepLoop).then(resolve);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment