Created
March 10, 2020 18:24
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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