perf: reduce first task's delay in `consumer`

This commit is contained in:
Menci ❤️ 2022-03-12 23:17:20 +08:00 committed by GitHub
parent 5e824af1b8
commit 92b7c92b01
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 3 deletions

View File

@ -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) {
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) {
tasks.push(fn.bind(this, ...args));
if (timer == null) {
nextTask();
timer = setInterval(() => {
tasks.shift().call(this);
if (tasks.length <= 0) {
if (!nextTask()) {
clearInterval(timer);
timer = null;
}