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?
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>