This is node.js.
I have a function that might become an infinite loop if several conditions are met. Untrusted users set these conditions so for the purpose of this question please assume the infinite loop is unfixable.
Still I need a way to stop the infinite loop.
Here is some sample code for what i'm trying to do:
var infiniteloop = false;
var condition = true
function loop () {
while (condition) {
console.log('hi')
if (infiniteloop) {
condition = false
console.log('oh last one')
}
}
}
loop()
So a few questions based on what I'm trying to do.
infiniteloop
variable is set to true, the loop will stop right?infiniteloop
variable cannot be changed while it's looping if it's on the same process. I have to store the variable in a different process?Thanks for your help.
A solution based on a mix of the other proposals:
function Worker()
{
this.MaxIterations = 1000000;
this.Enabled = true;
this.condition = true;
this.iteration = 0;
this.Loop = function()
{
if (this.condition
&& this.Enabled
&& this.iteration++ < this.MaxIterations)
{
console.log(this.iteration);
setTimeout(this.Loop.bind(this),0);
}
};
this.Stop = function()
{
this.Enabled = false;
};
}
var w = new Worker();
setTimeout(w.Loop.bind(w), 0);
setTimeout(w.Stop.bind(w), 3000);
Not sure this is optimal, but that should work as expected.
The use of setTimeout to resume the loop allows the main node.js event loop to process other events, such a w.Stop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With