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. :)
while(true)might break your browser or whatever you're using. You can usesetInterval()instead and useclearInterval()to stop the process.sleep, andwhile(true)is an incredibly terrible idea. What you could do is make sure that whenever functions that should be stoppable start, the register a customstopfunction to some global "stop functions, tied to the function name" manager. Which you'll have to write yourself.slieepfunction such that it checks a variable to see if it should continue sleeping. Set that variable to false in your "stop process" function.