Search code examples
node.jsasynchronouswhile-loopnonblockingpid

How to Write an Asynchronous While Loop in Node.JS


I am writing a node.js app for to help automate some of my home brewery. One of the modules I am using is a PID algorithm to control outputs so that they maintain certain setpoints. I am currently doing this via a while loop, but am thinking that this code will be blocking. Any help making this more effecient and asynchronous would be greatly appreciated. Here is my control loop:

device.prototype.pid_on = function(){
    while(this.isOn){
        this.pid.set_target(this.target); // make sure that the setpoint is current
        var output_power = this.pid.update(this.current_value); // gets the new output from the PID
        this.output.set_power(output_power);
    };
};

I have changed it a little for readability, but that is basically it. It will just loop, adjust the output, then feedback the new input value. I want the loop to continue to run until the device is turned off.

Obviously, I need this to be non-blocking so that I can continue to control other devices while the pid is running.

Currently, i just call the equivalent of device.pid_on(); in my code.

One idea I had is to use an empty callback, would that make this non blocking?

device.prototype.pid_on(calback){
    while (this.isOn){...};
    callback();
};

//call later in code
device.pid_on(function(){});

Thanks for any/all help!


Solution

  • It is better to avoid the while loop.

    device.prototype.pid_on = function() {
      var that = this;
      if ( this.isOn ) {
    
        ... do stuff
    
        process.nextTick(function() {
          that.pid_on();
        });
      }
    };
    

    Or

    device.prototype.pid_on = function() {
      var that = this;
      if ( this.isOn ) {
    
        ... do stuff
    
        setTimeout(function() {
          that.pid_on();
        }, 0);
      }
    };