Javascript在运行Web应用程序时连续从服务器获取数据

时间:2020-06-18 16:34:29

标签: javascript asynchronous while-loop

我有一个小问题: 我想从正在运行的服务器中获取一个JSON文件,以每秒几次为表提供最新数据。 因此,我计划编写一个异步函数,该函数在启动时会调用,并在我的webapp运行时运行,但是运行此代码后,我的网页不再响应。我的想法是设置一个超时,因此它等待500毫秒,然后再次运行,但是显然不能那样工作。我能做的最好的事情是什么? 感谢您的帮助。

let running = false;
//called on start
function run() {
    //some code
    running = true;
    getLatestData();
    //some code
}

async function getLatestData() {
while (running) {
    setTimeout(() => {
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
            //some code (JSON parse, set html and so on, that should work)
            }
        };
        xmlhttp.open("GET", "/api/data", true);
        xmlhttp.send();
    }, 500);
}

0 个答案:

没有答案
相关问题