Deadline Budget Caps Async Work Batches
Check the clock before each item, stop the moment a time budget runs out, and hand the untouched tail to the next tick instead of timing out mid-item.
Code
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 每项任务模拟 40ms 工作量
async function processItem(item) {
await sleep(40);
return `${item}:ok`;
}
// 在时间预算内尽量多做:每项开工前先看钟,超时立即让出
async function runWithinBudget(items, budgetMs) {
const deadline = Date.now() + budgetMs;
const results = [];
for (const item of items) {
if (Date.now() >= deadline) break;
results.push(await processItem(item));
}
return { results, remaining: items.slice(results.length) };
}
const queue = ['a', 'b', 'c', 'd', 'e', 'f'];
const within100 = await runWithinBudget(queue, 100);
console.log('100ms budget done:', within100.results.length, within100.results);
console.log('deferred:', within100.remaining);
const full = await runWithinBudget(queue, 1000);
console.log('1s budget done:', full.results.length, 'deferred:', full.remaining.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
100ms budget done: 3 [ 'a:ok', 'b:ok', 'c:ok' ]
deferred: [ 'd', 'e', 'f' ]
1s budget done: 6 deferred: 0Check the clock first
runWithinBudget computes deadline = Date.now() + budgetMs once, then tests Date.now() >= deadline before starting each item. The 100ms budget with 40ms items completes three of six and reports the untouched tail via items.slice(results.length).
Why this beats mid-item aborts
The loop only breaks between items, so a task already in flight always finishes and pushes its result — there are no half-processed entries, and the deferred tail is a clean slice of the original queue.
Scaling the budget
The second run uses a 1000ms budget, which fits all six items (1s budget done: 6, deferred: 0), demonstrating that the same loop scales with the allowance rather than the item count.
Interactive Tools for This Topic
FAQ
- Why check the deadline before each item instead of aborting mid-item?
- Breaking between items keeps every result complete; the deferred tail is a clean slice and no half-processed state exists.
- How is the deferred tail computed?
- results.length is the count of completed items, so items.slice(results.length) is exactly the untouched remainder.
Report a problem with this exampleOpens a pre-filled issue on GitHub.