我一直在关于类似问题的Stack Overflow上看一些其他问题。据说这个问题是由函数递归引起的,但我不能100%确定这是否是相同的情况 - 正如您将在下面看到的那样。
这是罪魁祸首函数,抛出错误:
/* inits AND parses research projects from database */
Game.prototype.initAndParseResearch = function(city, research){
var research = JSON.parse(research);
var d = new Date().getTime();
//object that contains active research projects
var projects = research.active;
//loop through each active project and "init" the research
for(var project in projects){
var obj = this.GameCfg.research_projects[project];
var timeUntil = (projects[project].started + (obj.time * 60 * 1000)) - d;
//minimum 0 - don't want a negative time for setTimeout()
if(timeUntil < 0){
timeUntil = 0;
}
//start timeout
var timeout = setTimeout(function(){
console.log('YOU FAILED.');
//this.researchFinished(city, project);
}.bind(this), 5000);
city.research = research;
city.research.active[project] = {
timeout : timeout
};
}
}
针对细节抛出的错误:
C:\xampp\htdocs\node_modules\mysql\lib\protocol\Parser.js:82
throw err;
^
RangeError: Maximum call stack size exceeded
C:\xampp\htdocs>
现在,罪魁祸首似乎是当函数试图存储从setTimeout
返回的句柄时。为什么我不能存储超时参考?我可以不存储它并使一切顺利运行,但如果我需要运行clearTimeout
,我就不会引用超时对象。
更新代码
/* inits AND parses research projects from database */
Game.prototype.initAndParseResearch = function(Player, city, research){
var research = JSON.parse(research);
var d = new Date().getTime();
//object that contains active research projects
var projects = research.active;
//loop through each active project and "init" the research
for(var project in projects){
var obj = this.GameCfg.research_projects[project];
var timeUntil = (projects[project].started + (obj.time * 60 * 1000)) - d;
//minimum 0 - don't want a negative time for setTimeout()
if(timeUntil < 0){
timeUntil = 0;
}
city.research = research;
//start timeout
var timeout = setTimeout(function(){
this.researchFinished(Player, city, project);
}.bind(this), timeUntil);
Player.timeouts['research_'+project] = timeout;
}
}