waitFor

Polling for something until a condition becomes true, like described in the blog post JavaScript waitFor Polling by David Walsh, has long been on my list of things that could be useful at some point. This week I had a use case within a Vue/TypeScript frontend app. David´s code provided a delightful solution. I did some adjustments for TypeScript syntax.

export async function waitFor(condition: () => any, pollMillis = 50, timeoutMillis?: number) {
const startTime = Date.now()

while (true) {
//check timeout first
if (timeoutMillis !== undefined && Date.now() > startTime + timeoutMillis) {
throw `Condition ${condition} not met before timeout of ${timeoutMillis} ms`
}

//check condition
const result = await condition()
if (result) {
return result
}

//wait for pollMillis until doing the next check of the condition
await new Promise((resolve) => setTimeout(resolve, pollMillis))
}
}

I used it like:

//go ahead from here only if no loading operation is in progress
await waitFor(
() => loadingStore.loading == false,
//check the above condition every 500 milliseconds
//and do not set a timeout to end the polling
500)
Comments