35 lines
1.2 KiB
TypeScript
35 lines
1.2 KiB
TypeScript
import {fault} from '../canvas-core/values.ts';
|
|
|
|
export type ImportScheduling = {
|
|
now?: () => number;
|
|
yieldTask?: () => Promise<void>;
|
|
frameBudgetMs?: number;
|
|
};
|
|
|
|
/** A soft time slice with a work threshold, even when the clock is coarse.
|
|
* The caller bounds each indivisible parse/decode operation separately. */
|
|
export function createImportBudget(signal: AbortSignal, options: ImportScheduling = {}) {
|
|
const budget = options.frameBudgetMs ?? 6;
|
|
if (!Number.isFinite(budget) || budget <= 0) throw fault('invalid_import_budget');
|
|
const now = options.now ?? (() => performance.now());
|
|
const yieldTask = options.yieldTask ?? (() => new Promise<void>(resolve => setTimeout(resolve, 0)));
|
|
let started = now(), work = 0, unchecked = 0;
|
|
return {
|
|
step(units = 1): Promise<void> | undefined {
|
|
work += units;
|
|
unchecked += units;
|
|
if (unchecked < 128 && work < 16384) return;
|
|
unchecked = 0;
|
|
if (signal.aborted) throw fault('import_aborted');
|
|
const elapsed = now() - started;
|
|
if (work < 16384 && elapsed >= 0 && elapsed < budget) return;
|
|
return (async () => {
|
|
await yieldTask();
|
|
if (signal.aborted) throw fault('import_aborted');
|
|
started = now();
|
|
work = 0;
|
|
})();
|
|
},
|
|
};
|
|
}
|