Search code examples
javascriptroboticscylon.js

Stack Overflow - Recursive Callback - JavaScript


I am writing some motor controls with node.js using cylon.js. I have a servo, which when you give it an angle to go to has a callback function. When it finishes that function, I want to do another reading, and give it a new angle, with the callback to do another reading...so forth and so on.

the current code is:

function ControlServo(servo, angleSensor){
robo.servo.angle(angleSensor.Read(), controlServo(servo, angleSensor));
}

That gets stack overflowed in like a quarter second.


Solution

  • A better way to solve this is using a timeout instead of recursing. This ends up calling your function on the next tick, which will never overflow.

    function ControlServo(servo, angleSensor){
        robo.servo.angle(angleSensor.Read(), function() {
            setTimeout(function() { ControlServo(servo, angleSensor)}, 0);
        });
    };
    

    You could shorten this by moving the timeout into the servo.angle function, but you might need it to be a callback for other uses. The method above requires no other change, since the callback is just setting the timeout.

    Another option is setImmediate, which appears to put the function call at the end of the current tick, instead of the beginning of the next one. Since setTimeout will always introduce a slight delay, setImmediate might be faster; however, I don't know what other tradeoffs might be made using this as I haven't used it much myself.