Created
June 3, 2019 18:39
-
-
Save alexsasharegan/0d392f3e4bca58b4bfdb91d8cbbead46 to your computer and use it in GitHub Desktop.
Schedule multiple promise-based tasks on idle browser time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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