Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Javascript concurrency and asynchronous operations

I am trying to understand how javascript handle concurrency with this script:

let buffer = [], total = [], count = 0;

const a = setInterval(() => {
  buffer.push(count);
  count++;
}, 1);

const b = setInterval(async () => {
  await new Promise(resolve => setTimeout(resolve, 500));
  total = [...total, ...buffer];
  buffer = [];
}, 1);

setTimeout(() => {
  clearInterval(a);
  clearInterval(b);
  console.log(total.length + " elements");
  for (let i = 0; i < total.length; i++) {
    if (i !== total[i]) {
      console.log("Error on " + i);
    }
  }
}, 10000);

Example of output:

8227 tries
Done !

From what I understand, intervals A and B will run in a single thread, and while interval B is waiting for the promise to resolve, interval A will keep running. However interval A will never be able to run after the promise is resolved and B's execution is resumed, so I shall never see an Error on x, is that correct ?

I tried to replace the interval like below and get errors, so I think I am correct, but I'd like to be 100% sure about this.

const b = setInterval(async () => {
  total = [...total, ...buffer];
  await new Promise(resolve => setTimeout(resolve, 500));
  buffer = [];
}, 1);
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!