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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With