会递归“setTimeout”吗?函数调用最终会杀死 JS 引擎吗?
假设我需要大约每 10 秒从服务器获取一些数据。我将有一个通过 AJAX 获取数据的函数,然后调用 setTimeout 再次调用该函数:
function GetData(){
$.ajax({
url: "data.json",
dataType: "json",
success: function(data){
// do somthing with the data
setTimeout(GetData, 10000);
},
error: function(){
setTimeout(GetData, 10000);
}
});
}
如果有人整天打开网页,它可能会收到数千次递归函数调用。
我不想使用 setInterval 因为这没有考虑网络延迟。如果网络繁忙并且需要 15 秒来处理请求,我不想在获得 AJAX 超时之前再次询问。
处理需要定期调用的函数的最佳方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有实际的递归,因为对 GetData 的调用被延迟,并且 JavaScript 上下文同时被破坏。所以它不会使 JS 引擎崩溃。
对于您的代码示例,这基本上是在 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.
For your code sample, this is basically what will happen at the JS engine level: