为了避免炸毁堆栈,我想在javascript中递归时放弃堆栈,一种解决方案是使用setTimeout和timeOut 0.还有其他解决方案吗?提前谢谢你。
我想将大量用户导入数据库,并在作业完成后调用回调。这是代码:
function importUser(userBigCollection,callback) {
(function addUser() {
var record = userBigCollection.getOneRecord() ; //Pop one record from collection
db.insert(record, function(error) {
if (err) { callback(error); return }
if (userCollection.empty()) {
// All users have been created
callback();
}
else {
setTimeout(addUser, 0);
}
} })();
}
感谢您的回复!
答案 0 :(得分:0)
此递归代码最多可以运行10次递归:
function recursive(maxloops,othervars){
if(maxloops==0) return FALSE;
if(morerecursionneeded) return recursive(maxloops-1,othervars);
return endofrecursion(othervars);
}
recursive(10,whatevervars);