Skip to content Skip to sidebar Skip to footer

Using Javascript Async Instead Of Setinterval

Let's say I want to run the function update() every second. I can do that in two ways: async function interval() { await new Promise((res, req) => { setTimeout(res, 1000)

Solution 1:

Your question is asking difference between settimeout and setinterval to achieve repetition, I feel here there is no relevance of asycn/await, you have just used it to avoid calling same function in setTimeout. Or you might say the relevance is async/await is doing, what setTimeout does, however as pointed by Ayush, you do not have any option to cancel the loop, which you get with setTimeout So following link might answer your curiosity. setTimeout or setInterval? Thanks

Solution 2:

The difference is that your interval functions returns a promise for when it is finished. You will need to add a return though so that it works properly:

asyncfunctioninterval() {
  awaitnewPromise((res, req) => { 
    setTimeout(res, 1000)
  })
  update()
  returninterval()
//^^^^^^
}

Now when update throws an exception, the promise is rejected and you can .catch() the error. Also the interval recursive calls would stop running, in contrast to the setInterval which would just continue.

Also async/await syntax has the advantage that you can avoid recursion to create loops:

asyncfunctioninterval() {
  while (true) {
    awaitnewPromise((res, req) => { 
      setTimeout(res, 1000)
    })
    update()
  }
}

Post a Comment for "Using Javascript Async Instead Of Setinterval"