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?
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:
- Initialize JS engine
- Create GetData function context
- Execute GetData statements including "setTimeOut"
- "setTimeOut" instruct the JS engine to call a function in 10 seconds
- Destroy GetData function context
- 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").
- After 10 seconds, repeat from step 2. "futureCall" is destroyed.
精彩评论