pp-parachute
Version:
Airdrop JS Applications
49 lines (47 loc) • 1.48 kB
JavaScript
var Promise = require('bluebird');
//debounces a function by calling it first then timing out before calling it again
var debounceHead = function (ctx, fn, waitTime) {
var timeout = null;
var promise = null;
var resolve = null;
return function () {
promise = promise || new Promise(function(_resolve) {
resolve = _resolve;
});
var args = arguments;
if (!timeout) {
timeout = setTimeout(function () {
timeout = null;
promise = null;
resolve = null;
}, waitTime || 250);
resolve(fn.apply(ctx, args));
} else {
clearTimeout(timeout);
timeout = setTimeout(function () {
resolve(fn.apply(ctx, args));
timeout = null;
promise = null;
resolve = null;
}, waitTime || 250);
}
return promise;
}
};
//debounces a function by waiting for `wait` ms of not being called again before calling fn.
var debounceTail = function (ctx, fn, wait) {
var timeout = null;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait || 250);
};
};
module.exports = {
debounceHead: debounceHead,
debounceTail: debounceTail
};