zent
Version:
一套前端设计语言和基于React的实现
50 lines (49 loc) • 1.43 kB
JavaScript
export default function throttle(func, wait, options) {
if (options === void 0) { options = {}; }
var timerId;
var result;
var args;
var previous = 0;
var _a = options.immediate, immediate = _a === void 0 ? false : _a;
var later = function () {
previous = immediate === false ? 0 : Date.now();
timerId = null;
result = func.apply(void 0, args);
if (!timerId) {
args = null;
}
};
var throttled = function () {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
var now = Date.now();
if (!previous && immediate === false) {
previous = now;
}
var remaining = wait - (now - previous);
args = params;
if (remaining <= 0 || remaining > wait) {
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
previous = now;
result = func.apply(void 0, args);
if (!timerId) {
args = null;
}
}
else if (!timerId && immediate === false) {
timerId = setTimeout(later, remaining);
}
return result;
};
throttled.cancel = function () {
clearTimeout(timerId);
previous = 0;
timerId = args = null;
};
return throttled;
}