Skip to content

Instantly share code, notes, and snippets.

@znck
Created January 27, 2020 10:12
Show Gist options
  • Save znck/ee89a6ea36ea63beacdac4369a5bfc9e to your computer and use it in GitHub Desktop.
Save znck/ee89a6ea36ea63beacdac4369a5bfc9e to your computer and use it in GitHub Desktop.
Array.prototype.forEachNonBlocking
export async function forEachNonBlocking<T>(
arrayOrIterator: IterableIterator<T> | T[],
fn: (item: T) => void,
frameBudgetInMillis: number = 10
): Promise<void> {
const iterator = Array.isArray(arrayOrIterator)
? arrayOrIterator[Symbol.iterator]()
: arrayOrIterator;
return new Promise((resolve, reject) => {
function continueIteration() {
const start = Date.now();
while (true) {
const item = iterator.next();
if (item.done) {
resolve();
break;
}
try {
fn(item.value);
} catch (error) {
reject(error);
break;
}
if (Date.now() - start > frameBudgetInMillis) {
setTimeout(continueIteration, 0);
break;
}
}
}
continueIteration();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment