Last active
May 28, 2024 15:01
-
-
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
This file contains hidden or 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
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