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

170
Views
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 answers
Answer question

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 Report
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!