Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript stop an infinite loop

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.

  1. If the infiniteloop variable is set to true, the loop will stop right?
  2. How do I detect the infinite loop? Something that checks every 3 seconds would be good.
  3. The 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?
  4. Whatever detects the infinite loop needs to live in a different process? Ideally same process would be nice but whatever works?

Thanks for your help.

like image 457
Harry Avatar asked Jul 13 '12 18:07

Harry


1 Answers

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.

like image 144
Julien Ch. Avatar answered Sep 24 '22 21:09

Julien Ch.