简体   繁体   中英

Why is this callback function being called infinitely?

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM