Execute async code in the order it came in setInterval

settimeout
setinterval async
mdn setinterval
nodejs setinterval
javascript setinterval source code
mdn settimeout
settimeout vs setinterval
recursive settimeout

I want to execute the code inside setInterval in an order it comes.

In real-time I am fetching data from different endpoints and I want to execute the code in the sequence it calls. response Time for some fetch request might be more so I want it to wait for the next call(fetch request) till the current request does not complete.

const s = 100;

/* Request number */
let seqN = 0;

const request = requestNumber =>
  // Request will be done from 1 to 5 seconds
  setTimeout(() => {
    out(`Refresh request number ${requestNumber} is done`);
  }, requestResponseTime(1, 6) * s);

setInterval(() => {
  request(seqN++);
}, 1 * s);

/**
 * Response time could take more than
 * interval time
 */
function requestResponseTime(min, max) {
  return Math.random() * (max - min) + min;
}

// Debug printing
out("Applicaiton started");
function out(message) {
  console.log(`${new Date().toUTCString()}: ${message}`);
}

If I get your question well, you want to only execute a new request after the previous one has been completed?

OR

You are worried about setInterval being fired even when the previous one request hasn't been completed?

If yes, then you need to have a checker/flag that would check if the previous request has been completed or not.

A quick example would be:

var isLoading = false;
setInterval(() => {
 if(isLoading === true) return; // more like do nothing
 else {
  isLoading = true;
  // call your request function here
 }
}, 1 * s)

Ensure not to put the checker/flag inside your setInterval/setTimeout call. make it a global variable as you did for your seqN. This way it's content would only change when something actually happens.

Also, ensure to set isLoading to false inside your request function as soon as your request function is done processing.

how to run an async func in setInterval in javascript, setInterval(): Execute a specified block of code repeatedly with a fixed Depending on how processor-intensive these operations are, they can delay your async code even further, as any async code will execute We arrived at our final value of 17 via the formula 1000 milliseconds In order, these are:. The code will run, then wait 100 milliseconds before it runs again—so the interval will be the same, regardless of how long the code takes to run. The example using setInterval() does things somewhat differently. The interval you chose includes the time taken to execute the code you want to run in. Let's say that the code takes 40

well there are two ways first is that you make the first call and wait for response then you make the second call, the other is that you make all the calls first but you do your operation on them on the order they were called. I am guessing you are looking for the second one, so if they are all fetch calls you can do it like this:

function async sequentialCalls() {
  const firstCall = fetch(first);
  const secondCall = fetch(second);
  const thirdCall = fetch(third);

  const firstRespone = await firstCall
    ....operation on firstResponse

  const secondRespone = await secondCall
    ....operation on secondResponse

  const thirdRespone = await thirdCall
    ....operation on thirdResponse
}

as for the setTimeout I think you need to promisify the response to be able to use it with await

Cooperative asynchronous JavaScript: Timeouts and intervals , Recently, I came across a requirement where I had to call a function In order to understand why setInterval is evil we need to keep in mind a fact In case of asynchronous operations, setTimeInterval will create long in setInterval code block, it will not stop execution but keeps on running faulty code. This article explains, step-by-step, how the JavaScript engine works and interacts with browser APIs to be able to execute asynchronous code without blocking the normal thread of execution. First…

I am able to achieve the functionality using recursion rather than the setInterval. I have given css code for this too so we can view the working properly.

index.js
import "./styles.css";
const s = 1000;

/* Request number */
let seqN = 0;

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

function myData() {
  request(seqN++)
    .then(data => {
      out(data);
      delay(1 * s);
      myData();
    })
    .catch(err => {
      console.log("err", err);
      seqN--;
      myData();
      // out(err);  
    });
}
myData();

// Failed request simulation
// DON'T CHANGE THE CODE AFTER
function request(requestNumber) {
  return new Promise((resolve, reject) => {
    const isOK = Math.random() >= 0.5;

    setTimeout(
      () =>
        isOK
          ? resolve(`${requestNumber} is <strong>OK</strong>`)
          : reject(`${requestNumber} is <span>KO</span>`),
      requestResponseTime(1, 6) * s
    );
  });
}

/**
 * Response time could take more than
 * interval time
 */
function requestResponseTime(min, max) {
  return Math.random() * (max - min) + min;
}

// Debug printing
out("Applicaiton started");

function out(message) {
  // console.log(`${new Date().toUTCString()}: ${message}`);
  document.getElementById(
    "app"
  ).innerHTML += `<pre>${new Date().toUTCString()}: ${message}</pre>`;
}

style.css
body {
  font-family: sans-serif;
}

strong {
  color: green;
}

span {
  color: red;
}

Why not to use setInterval, By following this rule, you ensure that Hooks are called in the same order each He talked to brewers, tasted his share of alt and came home with the inside dope Use setInterval to execute a function repeatedly, pausing for a period of time� setInterval simply queues the code to run once the current call stack is finished executing. This can be useful for some things. So yes, it's asynchronous in that it breaks the synchronous flow, but it's not actually going to execute concurrently/on a separate thread. If your goal is background processing, have a look at webworkers.

Async Inside Setinterval, A thread is another running program whose execution may be interleaved with to reflect light at another nest, encoding data as a sequence of quick flashes. As an example, the setTimeout function, available both in Node.js and in Our implementation calls console.log so that we can verify that the request arrived. Also the interval recursive calls would stop running, in contrast to the setInterval which would just continue. Also async/await syntax has the advantage that you can avoid recursion to create loops: async function interval() { while (true) { await new Promise((res, req) => { setTimeout(res, 1000) }) update() } }

Asynchronous Programming :: Eloquent JavaScript, Asynchronous thread-safe function calls setTimeout(msecs[, callback]); response.socket; response. Because of this, it is deemed necessary to bring down the process quickly in order to prevent an unintentional abort in the future. runtime deprecation with the notable exception that they are turned off by default and will� setInterval vs setTimeout setTimeout: sets a timer which executes a function or specified piece of code once the timer expires. setInterval: repeatedly calls a function or executes a code snippet, with a fixed time delay between each cal

Node.js v14.7.0 Documentation, There is a single main thread (a.k.a the Event-Loop) that executes all these why was the async code blocked without the setTimeout() call? why did When something similar happened to me, I turned to Google for answers. In order to understand why setInterval is evil. Thanks for the detailed explanation of setInterval in sync and async contexts, but why is it this "evil"? With a proper understanding of how the js event loop works, it's easy to understand the reason why a "new rhythm" gets established in the sync case, and why it doesn't in the async case.

Comments
  • So what is current behavior of this code?
  • Right now this code does not wait for 1st response to finish. whichever response finished 1st it will give an output that's why we can see the sequence is not in order.
  • @AmeyZulkanthiwar Are you OK with requests happening at non-fixed time intervals? I mean, is it OK if second request happens 1s after first then third request happens 2.5s after second?
  • Yes, That's what I mean. But the sample code that you gave it did not work.
  • @CreativeJoe You forgot to set isLoading to false after receiving a request thereby converting this setInterval to a setTimeout
  • Here is a link to my code sample. codesandbox.io/s/serverless-cache-8wy4k It still did not work.
  • Re-read my answer. Check out the last part. You are to set isLoading back to false in your request function
  • behind the hood, this code is losing some requests.