[英]setTimeout causes stack overflow
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. 您有一个无限循环。
setTimeout
expects the first parameter to be a callback function - you're actually invoking the waitForRawData
function then and there. setTimeout
期望第一个参数是一个回调函数-您实际上是在waitForRawData
然后调用waitForRawData
函数。 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 . 在没有包装功能的情况下, 现在正在调用相同的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.