Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Kelerchian/3824ca4ce1be390d34c5147db671cc9b to your computer and use it in GitHub Desktop.
Save Kelerchian/3824ca4ce1be390d34c5147db671cc9b to your computer and use it in GitHub Desktop.
Example Code for: Is there any programmatic way to break infinite loop in NodeJS?
// Question: https://stackoverflow.com/questions/60623418/is-there-any-programmatic-way-to-break-infinite-loop-in-nodejs
const example = () => {
const infiniteLoopWithSignal = async controller => {
let iteration = 0;
while (true) {
if(controller.isStopped) break;
console.log("Iteration: ", iteration++);
await new Promise(resolve => setTimeout(resolve, 1000));
}
console.log("Stopped!");
};
const controller = {
isStopped: false
};
infiniteLoopWithSignal(controller);
// mutate signal from outisde
setTimeout(() => {
controller.isStopped = true;
}, Math.floor(Math.random() * 10000 + 5000));
};
example();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment