在我问之前,我已经在寻找我的问题,但我仍然找不到答案,这可能是我的错误或其他事情,我做错了。
问题是,我想向XMLHttpRequest
服务器发出一个localhost
请求,但是在请求完成后,我希望向相同的目标/url示例发出相同的XMLHttpRequest
请求,如下所示:action/g
req.repeat = function(rnd = null) {
if(rnd == null) {
rnd = getrandint();
}
var data;
data = new FormData();
data.append('data', 'hay');
if(isset(xhr[rnd]) && xhr[rnd] == window.XMLHttpRequest) {
xhr[rnd].abort();
}
xhr[rnd] = new XMLHttpRequest();
xhr[rnd].open('POST', url+'action/g', true);
xhr[rnd].onreadystatechange = function() {
if(this.readyState == 4) {
req.repeat(rnd);
}
}
xhr[rnd].send(data);
}
我想代码运行得很好,但是如果XMLHttpRequest
请求只需要10 is就能从服务器获得响应,那么这个函数每10 is就会快速重复一次。
在再次执行setTimeout()
之前,我尝试使用req.repeat()
来处理这个问题,但我想这不是正确的。因为,如果XMLHttpRequest
请求占用3000 me,而我将setTimeout()
添加到1000 me,那么XMLHttpRequest
只会每4000 me重复一次,这对我来说是慢下来的。
我想在1000毫秒时不断重复,如果XMLHttpRequest
请求需要1200毫秒才能从服务器接收响应,超过1000毫秒的重复将不间断地执行。
但是我没有找到一种方法,甚至使用setInterval()
。
函数外部的信息var xhr = new Array();
。
请帮帮忙,我有什么建议
发布于 2018-10-12 12:57:34
我已经找到了一个答案,我自己的问题,没有使用任何websocket,这里的代码。
req.repeat = function(code = 0) {
var time;
var code, parent;
time = new Array();
while(code == 0) {
code = getrandint();
}
return {
execute: function(par, url, fun) {
var data, lim;
lim = 1500; // in miliseconds
data = new FormData();
data.append('data', par);
if(xhr[code] == window.XMLHttpRequest) {
xhr[code].abort();
}
xhr[code] = new XMLHttpRequest();
xhr[code].open('POST', meurl+'url', true);
xhr[code].onreadystatechange = function() {
if(xhr[code].readyState == 4) {
time['last'] = new Date();
time['diff'] = time['last'].getTime()-time['begin'].getTime();
if(isfun(fun)) {
fun(xhr[code]);
}
parent = new req.repeat(code);
if(time['diff'] > lim) {
parent.execute(par, url, fun);
} else {
tim = setTimeout(function() {
parent.execute(par, url, fun);
}, lim-time['diff']);
}
}
}
time['begin'] = new Date();
xhr[code].send(data);
}
}
}
谢谢你的帮助,但当我读到websocket更好的工作,但我仍然学习到websocket解决方案我的问题。
https://stackoverflow.com/questions/52763828
复制相似问题