Skip to content Skip to sidebar Skip to footer

How To Await Inside Setinterval In Js?

I have a code segment that looks like this: async function autoScroll(page, maxDate = null) { await page.evaluate(async () => { await new Promise(async (resolve, reject) =

Solution 1:

Use the following code:

setInterval(async () => {
    awaitfetch("https://www.google.com/") 
}, 100);

Solution 2:

Turn the interval function into a recursive setTimeout function instead, that way you can initialize a timeout for the next iteration once the function has finished.

asyncfunctiondoScroll() {
  window.scrollBy(0, scrollHeight);
  const scrollTop = document.documentElement.scrollTop;
  let lastDate = null;
  if (maxDate) {
    const html = newXMLSerializer().serializeToString(document.doctype) + document.documentElement.outerHTML;
    awaitextractDate(html).then((date) => {
      lastDate = date;
    });
  }
  if (scrollTop === lastScrollTop ||
      (maxDate && lastDate && maxDate.getTime() >= lastDate.getTime())) {
    // No need to `clearInterval`:resolve();
  } else {
    lastScrollTop = scrollTop;
    // Recursive setTimeout:setTimeout(doScroll, 2000); // <------------------
  }
}
setTimeout(doScroll, 2000);

Solution 3:

I generally opt for this solution. I think it's cleaner:

functiondelay(ms) {
  returnnewPromise(resolve =>setTimeout(resolve, ms))
}

asyncfunctionloop() {
  while (/* condition */) {
    /* code to wait on goes here (sync or async) */awaitdelay(100)
  }
}

Your loop function will return a promise. You can wait for it to stop looping, or you can discard it.

Solution 4:

Make the interval a function instead and use setTimeout to queue the future function call.

const interval = asyncfunction () { // instead of setInterval

Then use setTimeout function where you want to to queue the future call:

setTimeout(interval, 2000);

Fiddle example: http://jsfiddle.net/t9apy3ec/5/

Solution 5:

If someone wants an updated solution there is react-timeout which cancels any lingering timers automatically when wrapped component is unmounted.

More info

https://www.npmjs.com/package/react-timeout

npm i react-timeout

While using await you can do something like this

  handleClick = async() => {
    try {
      await this.props.getListAction().then(()=>{
        this.timeOut = this.props.setTimeOut(this.handleClick, 10000);
      });

    } catch(err) {
      clearTimeout(this.timeOut);
    }
  }

Post a Comment for "How To Await Inside Setinterval In Js?"