The main distinction lies in the fact that your interval
function returns a promise to signal when it has completed its task. It is imperative to include a return
statement to ensure proper functionality:
async function interval() {
await new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})
update()
return interval()
//^^^^^^
}
With this setup, when an error occurs while executing the update
function, the promise will be rejected and you can handle the error using .catch()
. Additionally, the recursive calls within the interval
function would cease, unlike with setInterval
which would continue indefinitely.
Another advantage of using the async
/await
syntax is that it eliminates the need for recursion to create loops:
async function interval() {
while (true) {
await new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})
update()
}
}