Created
January 27, 2020 10:12
-
-
Save znck/ee89a6ea36ea63beacdac4369a5bfc9e to your computer and use it in GitHub Desktop.
Array.prototype.forEachNonBlocking
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
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