使用XMLHttpRequest超时

所以我试图使用XMLHttpRequest的超时属性来“恢复”我的程序,当一个数据请求超时。 基本上,如果它检索数据失败,我希望它再次尝试。 目前我的代码看起来像这样(完整的URL被删除,以适应所有的整齐):

function pullRequest(){ var xhr = new XMLHttpRequest() xhr.onreadystatechange = function() { if (this.readyState === 4) { jsonDecode = this.responseText; json = JSON.parse(jsonDecode); ask = (json.result.Ask); bid = (json.result.Bid); } } xhr.open("GET","<URL>",true); xhr.send(); } 

我不完全遵循如何实现超时属性,或者如果它甚至要做我想要的。 我在xhr.open之后添加了以下两行,但是它抛出了错误:

  xhr.timeout = 5000; xhr.ontimeout = pullRequest() 

基本上在我的脑海里,如果超时,再次运行pullRequest函数。 我相信这可能不是一个好主意,但我没有足够的经验知道为什么。 对于什么是值得的错误片段如下:

 ...\node_modules\xmlhttprequest\lib\XMLHttpRequest.js:165 settings = { ^ RangeError: Maximum call stack size exceeded at exports.XMLHttpRequest.open 

任何关于如何实现我的目标的build议,或者是对某些能够帮助我的文献有所帮助,我们将不胜感激。

谢谢!

问题是你在调用 pullRequest

 xhr.ontimeout = pullRequest() // ------------------------^^ 

由于它立即调用自己,然后再次调用自己,并再次调用自己等等,当达到环境的最大recursion级别时,它最终会耗尽堆栈。

你不想在那里调用它,你只是想把函数引用分配给ontimeout所以如果超时发生,你的函数被调用:

 xhr.ontimeout = pullRequest // No () ------------------^