我试图让网络 worker 每秒左右轮询同一台计算机上的网络服务器接口(interface)。我读过的大多数文章都说要避免 setInterval 并使用 setTimeout 来代替,但我还没有找到使用 AJAX 而不是 Jquery 的示例。
到目前为止我的代码如下:
(function poll() {
setTimeout(function() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
responseObject = JSON.parse(xhr.responseText);
var newContent = '';
newContent += responseObject.cmd;
console.log(newContent);
}
}
xhr.open('GET', 'http://localhost:8194/screen_update/1000', true);
xhr.send(null);
setTimeout(poll, 1000);
}, 1000);
})();
首选的输出是每秒轮询一次服务器,理论上这足以让响应通过。我一次只需要一个请求,因此如果我最终收到一个请求花费超过一秒的时间,它只会转储该请求(而不是将其排队)并发出一个新请求。
上面的代码轮询正常,但没有完成 2 秒,所以我显然把我的 setTimeout 搞混了。我在哪里更正此代码?
最佳答案
我几天前就这么做了……虽然它可能不是最优雅的,但到目前为止效果很好。 我让工作人员处理超时/检查间隔,而不是主 JS。所以我想这是 UI 不需要处理的另一件事。这是我的 worker 代码:
function checkStatus() {
console.log("statusCheck started");
var ajaxRequest;
try { ajaxRequest = new XMLHttpRequest(); // Opera 8.0+, Firefox, Safari
} catch (e) { try { // Internet Explorer Browsers
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) { try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { // Something went wrong
console.error("AJAX not possible");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) {
self.postMessage(ajaxRequest.responseText);
var timer;
timer = self.setTimeout(function(){
checkStatus();
}, 1000);
}
}
ajaxRequest.open("GET", "/worker_statusCheck.php", true);
ajaxRequest.send(null);
}
this.onmessage = function(e){
checkStatus(); // the message comes in just once on pageLoad
};
关于javascript - 使用 setTimeout 进行 AJAX Webworker 轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38569266/