简体   繁体   中英

How to set a timeout so that an await takes at least a certain amount of time?

For visual reasons, I need to show a certain component for at least 1000ms. The flag for the component is toggled before an async call is made and it's turned back off after the call finishes.

I need the component to show for 1 second if the async call is shorter than that, and for the time the async call requires if that is longer than 1 second.

That is, I have two cases.

1.) time needed by async <= 1s: show the component for 1s 2.) time needed by async > 1s: show the component for the time needed by the async call. And not that time + 1s

How would you approach this? I played around with setting timeouts, but in that case that times seem to add up.

For example, to wait for 1 second in an async function:

await new Promise(resolve => setTimeout(resolve, 1000))

You could also extract this into a more convenient utility:

function wait(seconds) {
  return new Promise(resolve => setTimeout(resolve, seconds * 1000))
}

await wait(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM