If you want to iterate something without stopping instead another function asks for it:
I would not do that. I believe every function should control itself. If the function dedicated to stop another function append to fail, the cost in term of ressources and time to fix it may become problematic.
Instead, I'd create a function calling another function after checking something else (cookie, data, variable).
const checkSomething = () => {
// var in parameter, cookie, data from API, etc
// if necessary throw new Error
if (something) return true;
return false;
};
const something = () => {
console.log('I did that');
};
const periodicallyDoSomething = () => {
try {
let continueDoingSomething = checkSomething();
while (continueDoingSomething) {
something();
continueDoingSomething = checkSomething();
}
} catch (e) {
console.error(e.message);
} finally {
console.log('I did it!');
}
};
// run it, or export it as in module.exports
If you want a function to do something that takes a lot if time while still being able to stop it externally, like a classic CTRL+C:
This should be inside your function.
I believe that a function dedicated to do something should be the same function finishing it.
Try/catch/finally, like I used it juste before, may be interesting.
Have a happy coding time. :)