I have the following template in my project:
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function foo (x) {
await sleep(3000)
await asyncTask()
await foo()
}
It should repeat the job (foo
) until a specific event is received. However, I am having a hard time finding a way to stop the recursion. Seems like there is no way to achieve it with this approach.
In some other, I could not find an answer/comment to describe how to terminate this kind of function.
One potential way would be using setInterval
with an async function, but seems like setInterval
is supposed to work with sync callbacks only.
(I've seen there are some npm packages for this particularly, but I am trying to avoid adding a new dependency just for this)
Edit: Seems like this solution also works:
let timeoutId
async function loop (socket) {
await asyncTask()
timeoutId = setTimeout(
async () => await loop(socket),
3000
)
}
socket.on('event', () => clearTimeout(timeoutId))