问题
I am have the following code. it causes a stack overflow exception.
any idea what did I do wrong?
var myApi = {
rawData: null,
initData: function() {
// ajax call to get data and populate myApi.rawData, max 10 seconds
},
waitForRawData: function(callback) {
if(myApi.rawData === null || myApi.rawData.length ===0) {
window.setTimeout(myApi.waitForRawData(callback),1000); // complain this line stack overflow
}else{
callback();
}
},
updateHtmlWithNewData: function() {
// base on myApi.rawData update html element
},
workflow: function() { // this function call is invoke from page
myApi.initData();
myApi.waitForRawData(myApi.updateHtmlWithNewData);
}
}
回答1:
You have an infinite loop.
setTimeout
expects the first parameter to be a callback function - you're actually invoking the waitForRawData
function then and there. Which immediately invokes itself again, which immediately invokes itself again, which... you get the idea.
Do this:
window.setTimeout(function() { myApi.waitForRawData(callback) },1000);
When you pass it as a function, then the timeout can invoke it whenever you tell it to - in your case, a second later. Doing it without the wrapping function is calling that same code right now.
来源:https://stackoverflow.com/questions/14151744/settimeout-causes-stack-overflow