Home > database >  setInterval() wait time is after the previous one was called or after it was done? / how to control
setInterval() wait time is after the previous one was called or after it was done? / how to control

Time:10-27

I am trying to use setInterval to call an API that has rate limit for requests per seconds. I tried to use setInterval as a while loop, but I can't find info on when it starts the next round.

So if I do:

setInterval(() => {
    CallAPI();
    // Some proccessing
}, 300)

Will the next round start after the first one finishes or regardless of it? because order matter, and also timing can cause an error.

I can also try to do the same with setTimeout and a while loop like so:

while(true) {
setTimeout(() => {
    CallAPI();
    // do some proccessing
}), 300
}

But again, I am not sure when the next round of the loop will start.

And lastly I cheat my way through it and do

while(true) {
    await CallAPI();
    // Do proccessing
    await setTimeout(() => true, 300)
}

So what is the order for setTimeout() and setInterval() in a loop?

CodePudding user response:

Just call it when it is done executing. No need for a loop.

function fakeCall () {
  return new Promise((resolve) => {
    window.setTimeout(resolve, Math.random() * 2);
  });
}



function next() {
  window.setTimeout( async function () {
    await fakeCall();
    console.log(Date.now());
    next();
  }, 3000);
}

next();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You'll probably want to set up your loop as follows:

var TO_asyncLoop = null;
function asyncLoop(fn, ms){
  clearTimeout(TO_asyncLoop);
  TO_asyncLoop = setTimeout(() => { fn() }, ms)
}

var i = 0;
function doSomething(){
  // do somthing
  console.log("hi", i  );

  // when this "something" is finished, do it again:
  asyncLoop(doSomething, 500)
}

doSomething()
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related