递归的“setTimeout"函数调用最终会杀死 JS 引擎吗? [英] Will a recursive 'setTimeout' function call eventually kill the JS Engine?

查看:28
本文介绍了递归的“setTimeout"函数调用最终会杀死 JS 引擎吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要大约每 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:

  1. 初始化JS引擎
  2. 创建 GetData 函数上下文
  3. 执行包括setTimeOut"在内的 GetData 语句
  4. "setTimeOut" 指示 JS 引擎在 10 秒内调用一个函数
  5. 销毁 GetData 函数上下文
  6. 此时,在内存使用方面,我们又回到了第 1 步.唯一的区别是 JS 引擎存储了对函数的引用以及何时调用它(我们将此数据称为futureCall").
  7. 10 秒后,从第 2 步开始重复.futureCall"被销毁.

这篇关于递归的“setTimeout"函数调用最终会杀死 JS 引擎吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆