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

272
Visualizações
What is the better way to pause a lengthy operation in JavaScript?

I am processing unknown number of items in a loop. Processing each item takes variable time. As the overall operation is lengthy and to give the end user more control, I want to provide a pause button.
The items to process are provided by a third party generator function and I can't modify it. So total number of items is unknown.

Following is my attempt to implement the feature:

let processed = 0;
let paused = false;
let resume = () => {};

// a third party function, which I can't modify
async function* getItems() {
  for (;;) yield 1;
}

// placeholder for a lengthy operation
async function process(item) {
  return new Promise(resolve => setTimeout(resolve, 1000));
}

// is this a better way to implement pause?
async function enforcePause() {
  if (paused)
    return new Promise(resolve => {resume = resolve});
  else return Promise.resolve();
}

btn.addEventListener('click', () => {
  if (paused) {
    resume();
    paused = false;
    btn.textContent = 'Pause';
  } else {
    paused = true;
    btn.textContent = 'Resume';
  }
});

// a lengthy operation 
async function processAll() {
  for await (let item of getItems()) {
    await process(item);
    counter.textContent = ++processed;
    
    await enforcePause();
  }
}

processAll();
<p>Progress: <span id="counter">0</span></p>
<button id="btn">Pause</button>

My queries are:

  1. Is there a better way to implement this? Should I be looking for a library?
  2. If no, what improvements can be made to above code? any caveats?
  3. If the total number of items were finite and the items were stored in a collection, is there a better solution possible?
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