我有一个小问题: 我想从正在运行的服务器中获取一个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);
}