首页 > 解决方案 > 如何避免由于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 ++;
}

标签: javascriptarrays

解决方案


正如评论所说:$.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中的变量通常是驼峰式,而不是大写;常量是例外,因为它们通常是全大写。


推荐阅读