Skip to content

Instantly share code, notes, and snippets.

@mendes5
Last active May 28, 2024 15:01
Show Gist options
  • Save mendes5/89d7f48f4faae9793a50f436d5d01cb2 to your computer and use it in GitHub Desktop.
Save mendes5/89d7f48f4faae9793a50f436d5d01cb2 to your computer and use it in GitHub Desktop.
Process a list with configurable in the middle as to not block the main thread
type AsyncMapParams = {
timeout: number;
steps: number;
coolDown?: number;
}
const asyncMap = async <I, O>(inList: I[], fn: (input: I) => O, inParams: AsyncMapParams): Promise<O[]> => {
const params = Object.assign({}, {
timeout: 16,
coolDown: 16,
steps: 10_000,
}, inParams);
const outList = new Array<O>(inList.length);
let startTime = performance.now();
for (let i = 0; i < inList.length; i++) {
if (i % params.steps === 0) {
if (performance.now() - startTime > params.timeout) {
await new Promise(res => setTimeout(res, params.coolDown));
startTime = performance.now()
}
}
try {
outList[i] = fn(inList[i]);
} catch (error) {
outList[i] = error;
}
}
return outList;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment