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);
}
}
You have an infinite loop.
setTimeoutexpects the first parameter to be a callback function – you’re actually invoking thewaitForRawDatafunction then and there. Which immediately invokes itself again, which immediately invokes itself again, which… you get the idea.Do this:
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.