javascript - 如何避免由于http请求无限循环导致浏览器无响应
问题描述
我想以毫秒为单位从传感器获取数据,然后在十秒内计算平均值以根据平均值发出警报。问题是,只要将 while 循环设置为小于 1000 或一秒,并且当我将其设置为更大的数字(我希望循环无限工作并使用按钮功能停止),这段代码就会运行良好。我想知道是否有任何方法可以在 Javascript 中运行这个无限循环?这是我的代码:
const now = Date.now();
var epochTime = now;
//Arrey of the value
var Arrey = [];
Counter =0
while (epochTime<now+10000000) { //should be set infinite and stop with button
$.get('http://xxx/'+epochTime, function(data){
let myValue= data.data[354708094967841].crosscorrelations[0].value;
document.getElementById("demo").innerHTML +="<br/>"+ myValue ;
Arrey.push(myValue);
console.log(Arrey);
var sum =0;
console.log(epochTime);
if (Counter>=10000 && Counter%10000==0){
for ( i=Counter-10000; i<Counter; i++)
sum = sum + Arrey[i];
valueAverage= sum/10000;
console.log(valueAverage);
document.getElementById("valueAverage").innerHTML +="<br/>"+ valueAverage;
if (valueAverage>0.01){
alert("the value ave is high"); // ----> to check the code
}else{
alert("the value ave is low"); //-----> to check the code
}
}
console.log(Counter);
Counter++;
console.log(myValue); //get data from value in async version
});
epochTime ++;
}
解决方案
正如评论所说:$.get()
是异步的,所以它不会等待。您可以做的是将获取请求包装在一个函数中并从请求中调用该函数,从而创建一个循环。有点像这样:
var buttonClicked = false;
//Function simply wraps the get request so that it can be called at anytime
function getSensorData(){
$.get('http://xxx/'+epochTime, function(data){
let myValue = data.data[354708094967841].crosscorrelations[0].value;
document.getElementById("demo").innerHTML += "<br/>" + myValue;
Arrey.push(myValue);
console.log(Arrey);
var sum = 0;
console.log(epochTime);
if (Counter >= 10000 && Counter % 10000 == 0) {
for (i = Counter - 10000; i < Counter; i++)
sum = sum + Arrey[i];
valueAverage = sum / 10000;
console.log(valueAverage);
document.getElementById("valueAverage").innerHTML += "<br/>" + valueAverage;
if (valueAverage > 0.01) {
alert("the value ave is high"); // ----> to check the code
} else {
alert("the value ave is low"); //-----> to check the code
}
}
console.log(Counter);
Counter++;
console.log(myValue); //get data from value in async version
//Now that you're done with everything, you can check if the button is clicked and if it is, don't run the function again.
if (!buttonClicked){
getSensorData();
}
}
}
//Here we check if the button is clicked and change the variable when it is
$("#stopButton").click(function(){
buttonClicked = true;
});
另外,快速注意:javascript中的变量通常是驼峰式,而不是大写;常量是例外,因为它们通常是全大写。
推荐阅读
- node.js - 尝试在 Node.js / Puppeteer 中使用代理服务器时出错
- javascript - TS2307:找不到模块“./images/logo.png”
- javascript - 如何将搜索输入从类组件传递到单独的 api 组件
- c - 如何在c中停止control-d退出shell
- python - 如何使用 pd.Timestamp 函数将数据列更改为时间戳格式
- javascript - 我使用带有数据库的假 REST API。想要上线并拥有一个数据库接口
- javascript - 如何使用 for 循环从对象数组中添加值?
- angular - Angular5,在路由上,网址发生了变化,但它没有加载相同的页面
- python - 张量流中内置 MS-SSIm 函数的计算错误
- python - Python:透视数据集