0

I'm recursively calling a function and its callback, the done() function, is being called infinitely and I don't know why.

When I log i, it reaches the length of data and then the condition is met and it stops, but the done function is called infinitely. The done function is not recursive; why is it being called more than once? How can I get it to be called only once when the incrementer is equal to the length of data and nTwo is defined?

I think it may be because of the pre-increment of i, but I needed that otherwise I get an RangeError, Maximum Stack Exceeded.

function train(i, data, n, nTwo, func){
    console.log(i, i===data.length);
    if(i===data.length && nTwo===undefined) func();
    else if(i<data.length) (new Trainer(n)).workerTrain([data[i]], train(++i, trainingSet, l, y));
    else done();
}
function done(){
    console.log('first set of workers done');
    saveAs(new Blob([JSON.stringify(l.toJSON())], {type: "application/json"}), "l.json");
    train(0, yonTraining, y, undefined, finalTrainingCallback);
}
wordSmith
  • 2,993
  • 8
  • 29
  • 50
  • Please, add the needed code to create something testable: functions done(), func(), Trainer and Trainer.workerTrain are not explained. And please, use curly braces in you if...else conditions – Pablo Lozano May 27 '15 at 07:29
  • We need some more data. The only way `done()` is called is if `i > data.length`. And now after your edit it looks like `done` is calling `train` again with `0` for `i`, so it can be recursive in a way. – Omri Aharon May 27 '15 at 07:39
  • @OmriAharon updated with done's definition. – wordSmith May 27 '15 at 07:41
  • What do you have in `yonTraining` ? – Omri Aharon May 27 '15 at 07:43
  • I can see why done will end up being called infinitely (and also `train`), but I cant see how `done` is called in the first place. What is `i` and `data.length` at the entry point to the last `if` that invokes `done` ? – Omri Aharon May 27 '15 at 07:55
  • @OmriAharon they both equal 4. There are 4 objects in trainingSet which is what is first passed as data in the first train call elsewhere. Why does it go infinitely? – wordSmith May 27 '15 at 08:00
  • Because `done` calls `train` again, which will call `done` again and it's a loop. If `i === data.length === 4` then your `f(i===data.length && nTwo===undefined)` condition fails, check to see why. – Omri Aharon May 27 '15 at 08:02
  • please note the functions ARE recursive - https://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Indirect_recursion – Aprillion May 27 '15 at 08:31

1 Answers1

0

Clearly the function train is calling to the function done, which is calling again the function train. Then the function train increments the index i until its value is bigger than the data.length, calling again the done function

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59