Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Created June 3, 2019 18:39
Show Gist options
  • Save alexsasharegan/0d392f3e4bca58b4bfdb91d8cbbead46 to your computer and use it in GitHub Desktop.
Save alexsasharegan/0d392f3e4bca58b4bfdb91d8cbbead46 to your computer and use it in GitHub Desktop.
Schedule multiple promise-based tasks on idle browser time.
port async function idleMap<Item, Output>(
iterable: Iterable<Item>,
op: (item: Item) => Promise<Output>
): Promise<Output[]> {
return new Promise((resolve) => {
let iter = iterable[Symbol.iterator]();
let buf: Output[] = [];
async function process(deadline: RequestIdleCallbackDeadline) {
do {
let result = iter.next();
if (result.done) {
return resolve(buf);
}
buf.push(await op(result.value));
} while (!deadline.didTimeout);
requestIdleCallback(process);
}
requestIdleCallback(process);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment