Loop in javascript with ranges

Asked

Viewed 216 times

-3

I need to make a loop where at each iteration it wait 2 seconds until the next. I tried with setInterval, but saw that it does not work as I want... For it is asynchronous, so the loop runs normal, just calling the set interval that runs in its time... as I do so that there is a delay in each iteration?

function I did and does not work as accurate:

while ((!this.service.levelsLoaded)) {
      setInterval(function() { }, 2000);
}
  • What exactly do you need done? The snippet of code you put in is very small and doesn’t help with the answer... Try [Edit] your question to put more details.

  • ops I put if instead of while... and I need every iteration of while it gives like a Sleep... the way it is, it waits 2 seconds and then fires everything

1 answer

1

The best would be to assign the return value of setInterval there is a variable, run what you want every 2 seconds inside the callback of setInterval and, when you want to finish, call clearInterval providing the return of setInterval as argument. But, there is a way to keep your loop using async, await and Promise:

async function doSomething() {
  while ((!this.service.levelsLoaded)) {
    await new Promise(resolve => {
      // Faça alguma coisa...
      setTimeout(resolve, 2000)
    })
  }
}

Or, if you prefer to create a function for reuse:

async function sleep(time) {
  await new Promise(resolve => setTimeout(resolve, time))
}

async function doSomething() {
  while ((!this.service.levelsLoaded)) {
    // Faça alguma coisa
    await sleep(2000)
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.