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

171
Visualizações
Stop/pause node tasks after executing them

If I wait for user input in node and depending on it I execute a function and pass some parameters inside it is there any way to stop this function after it starts being executed? I am creating a node app that runs multiple tasks depending on user input and I have no idea how people can "pause" or "stop" some tasks after they start being executed.

I saw some people creating some automation stuff and having stop/pause functionality but how exactly do they achieve it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

We can do this by throwing an exception and catching after the main implementation. The app's state after stopping can be set in the catch block.

We can make a function that checks our stopped boolean, and throws an exception if it's true. We can then use it as a sort of checkpoint or stopping point throughout our function.

Here's an example:

Note that there are only two checkpoints. i.e. if it starts running Add(3) and you stop it, it'll still run Add(4)

let stopped = false;
stopButton.onclick = () => stopped = true;

const data = { result: 0 };

function checkpoint() {
  if (stopped) throw new Error();
}

async function add(data, num) {
  console.log(`Adding ${num}`);
  await new Promise((res) => setTimeout(res, 2000));
  data.result += num;
  return data;
}

(async () => {
  try {
    await add(data, 1);
    await add(data, 2);
    checkpoint();
    await add(data, 3);
    await add(data, 4);
    checkpoint();
    await add(data, 5);
    await add(data, 6);
    console.log('Done');
  } catch {
    console.log('Stopped running. Resetting program');
  }
})();
<button id="stopButton">Stop</button>

about 4 years ago · Juan Pablo Isaza Relatório
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