setTimeout causes stack overflow

人走茶凉 提交于 2019-12-14 02:16:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!