Created
January 30, 2015 22:00
-
-
Save modernserf/e09ba3aa9e5788803f97 to your computer and use it in GitHub Desktop.
Debounce Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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