redoc/src/utils/decorators.ts

42 lines
954 B
TypeScript
Raw Normal View History

2018-02-08 00:01:56 +03:00
function throttle(func, wait) {
let context;
let args;
let result;
let timeout: any = null;
let previous = 0;
const later = () => {
previous = new Date().getTime();
timeout = null;
2018-02-07 23:52:13 +03:00
result = func.apply(context, args);
2018-02-08 00:01:56 +03:00
if (!timeout) {
context = args = null;
}
2018-02-07 23:52:13 +03:00
};
return function() {
2018-02-08 00:01:56 +03:00
const now = new Date().getTime();
const remaining = wait - (now - previous);
2018-02-07 23:52:13 +03:00
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
2018-02-08 00:01:56 +03:00
if (!timeout) {
context = args = null;
}
2018-02-07 23:52:13 +03:00
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
2018-02-08 00:01:56 +03:00
}
2018-02-07 23:52:13 +03:00
export function Throttle(delay: number) {
return (_, _2, desc: PropertyDescriptor) => {
desc.value = throttle(desc.value, delay);
};
}