Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda