Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - Will a recursive 'setTimeout' function call eventually kill the JS Engine?

Let's say I have some data that I need to get from the server about every 10 seconds. I would have a function that gets the data via AJAX and then call setTimeout to call this function again:

function GetData(){
   $.ajax({
       url: "data.json",
       dataType: "json",
       success: function(data){
         // do somthing with the data

         setTimeout(GetData, 10000);
      },
      error: function(){
         setTimeout(GetData, 10000);
      }
   });
}

If someone leaves the web page open all day, it could get thousands of recursive function calls.

I don't want to use setInterval because that does not take into account network delay. If the network is busy and it takes 15 seconds to process the request, I don't want to ask it again before I get the AJAX timeout.

What is the best way to handle a function that needs to be called periodically?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's no actual recursion because the call to GetData is delayed and the JavaScript context is destroyed in the meantime. So it won't crash the JS engine.

For your code sample, this is basically what will happen at the JS engine level:

  1. Initialize JS engine
  2. Create GetData function context
  3. Execute GetData statements including "setTimeOut"
  4. "setTimeOut" instruct the JS engine to call a function in 10 seconds
  5. Destroy GetData function context
  6. At this point, in terms of memory use, we are back to step 1. The only difference is that the JS engine stored a reference to a function and when to call it (lets call this data "futureCall").
  7. After 10 seconds, repeat from step 2. "futureCall" is destroyed.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...