'is it possible to await for a promise response using setInterval?

Basically i have an timer, lets say the timer starts at 60 seconds and goes to 0 when it reaches 0 it makes an api call and the timer restarts, the issue im having is that when the timer reaches 0 it just restars without awaiting for the promise response, in someway i need for the timer to pause at 0 wait for the response and then start counting from 60 again, i tried using clearInterval() but it works only in the 1st countdown after it the timer just stops, here is my following code, i think it will be easier to understand

setInterval(async () => {
    document.querySelector('.timeh1').innerHTML = newInterval - i
    i++
    if(i >= newInterval){
        await apiCallReload(currency)                
        i = 0
    }
    }, 1000)

as you can see this function is executed each second and when the running time (i) reaches the timer limit (newInterval) it will call my apiCallReload() function and the timer will reset to 0 again, but the problem is that the timer resets without awaiting for the function promise ( it takes between 5 - 10 seconds to get the response from the api) is there an way/workaround that i can make the timer stops when it reaches 0, wait for the api response and then start counting again?



Solution 1:[1]

I think, you have to use setTimeout(), smth like this

let time = 60;

async function callback() {
  time = time - 1;
  if (time === 0) {
   await fetch('https://google.com');
   time = 60;
  }
  setTimeout(callback, 1000)
}

callback()

Solution 2:[2]

You could achieve the desired result using a while loop...

let waitTime = 3000

;(async ()=>{
  console.log('Started')
  while(true) {
      await new Promise(res=>setTimeout(res,waitTime))
      console.log('Waited', waitTime, 'ms')
      let randTime = 1000 + Math.random()*1000
      await new Promise(res=>setTimeout(()=>{console.log('your asnyc fun',randTime);res();},randTime)) //  your async func
  }
})()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 random322
Solution 2 atomh33ls