Home > Blockchain >  is it possible to await for a promise response using setInterval?
is it possible to await for a promise response using setInterval?

Time:05-14

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?

CodePudding user response:

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()

CodePudding user response:

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
  }
})()

  • Related