Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda