递归'setTimeout'函数调用最终会杀死JS引擎吗? [英] Will a recursive 'setTimeout' function call eventually kill the JS Engine?
问题描述
假设我每隔10秒就需要从服务器获取一些数据。我有一个函数通过AJAX获取数据,然后调用setTimeout再次调用此函数:
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.
我不想使用setInterval,因为它没有考虑网络延迟。如果网络繁忙且处理请求需要15秒,我不想在获得AJAX超时之前再次询问它。
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?
推荐答案
没有实际的递归,因为对GetData的调用被延迟了同时销毁JavaScript上下文。所以它不会使JS引擎崩溃。
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.
对于你的代码示例,这基本上是JS引擎级别会发生的事情:
For your code sample, this is basically what will happen at the JS engine level:
- 初始化JS引擎
- 创建GetData函数上下文
- 执行包含setTimeOut的GetData语句
- setTimeOut指示JS引擎在10秒内调用函数
- 销毁GetData函数上下文
- 此时,就内存使用而言,我们又回到了第1步。唯一的区别是JS引擎存储了对函数的引用以及何时调用它(让我们调用这个数据futureCall)。
- 10秒后,从步骤2开始重复。futureCall将被销毁。
- 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.
这篇关于递归'setTimeout'函数调用最终会杀死JS引擎吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!