mirror of https://github.com/Nofated095/Q2TG.git
perf: reduce first task's delay in `consumer`
This commit is contained in:
parent
5e824af1b8
commit
92b7c92b01
|
@ -10,14 +10,23 @@ export function debounce<TArgs extends any[], TRet>(fn: (...originArgs: TArgs) =
|
||||||
}
|
}
|
||||||
|
|
||||||
export function consumer<TArgs extends any[], TRet>(fn: (...originArgs: TArgs) => TRet, time = 100) {
|
export function consumer<TArgs extends any[], TRet>(fn: (...originArgs: TArgs) => TRet, time = 100) {
|
||||||
let tasks = [], timer: NodeJS.Timeout;
|
const tasks: Function[] = [];
|
||||||
|
let timer: NodeJS.Timeout;
|
||||||
|
|
||||||
|
const nextTask = () => {
|
||||||
|
if (tasks.length === 0) return false;
|
||||||
|
|
||||||
|
tasks.shift().call(null);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
return function (...args: TArgs) {
|
return function (...args: TArgs) {
|
||||||
tasks.push(fn.bind(this, ...args));
|
tasks.push(fn.bind(this, ...args));
|
||||||
|
|
||||||
if (timer == null) {
|
if (timer == null) {
|
||||||
|
nextTask();
|
||||||
timer = setInterval(() => {
|
timer = setInterval(() => {
|
||||||
tasks.shift().call(this);
|
if (!nextTask()) {
|
||||||
if (tasks.length <= 0) {
|
|
||||||
clearInterval(timer);
|
clearInterval(timer);
|
||||||
timer = null;
|
timer = null;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue