I found a code that could get the last modified time of a file on the server and have adapted it to my needs, it works fine but I get the warning below and reading about the code seems to be resource intensive for the users computer.
The code needs to react (reload) to a file being modified and print out the time since it was last modified.
I notice my computer is (slightly) sluggish when I have two windows open that use this code, perhaps this is the reason.

我可以做些什么来使其成为异步的呢?

主线程上的同步XMLHttpRequest被否决,因为它对最终用户的体验有不利影响.如需更多帮助,请拨打https://xhr.spec.whatwg.org/.

       <script>
            var pageload = new Date();
            function fetchHeader(url, wch) {
                try {
                    var req=new XMLHttpRequest();
                    req.open("HEAD", url, false);
                    req.send(null);
                    if(req.status== 200){
                        return req.getResponseHeader(wch);
                    }
                    else return false;
                } catch(er) {
                    return er.message;
                }
            }

            window.setInterval(function(){
                var time = Date.parse(fetchHeader("Akut.txt",'Last-Modified'));
                var d = new Date();
                var diffSec = Math.round((d - time) / 1000);
                document.getElementById("time").innerHTML = Math.trunc(diffSec/60) + " minutes"; // time since it was modified
                
                if ((d-pageload)/1000 > 10 && diffSec < 5 ){
                    location.reload();
                }
            }, 2500);
        </script>

I found this thread XMLHttpRequest is deprecated. What to use instead? and I have tried to modify the code but I can't get this code to give me the last modified time.
This just returns NaN.


             function fetchHeader(url, wch) {
                try {
                    var xhr = new XMLHttpRequest()
                    xhr.onreadystatechange = function() {
                        if (this.readyState === this.DONE) {
                            console.log(this.getResponseHeader(wch)); // assumed this would work but it doesn't
                        }
                    }
                    xhr.open("HEAD", url)
                    xhr.send()
                } catch(er) {
                    return er.message;
                }
            }

I need help with making this asynchronous. I have tried to read the xhr link from the warning but I'm not much of a Javascript developer so it's hard for me to find what I need to do.
Can someone point me in the right direction here?

推荐答案

以下是异步xmlhttp请求

const pageload = new Date(); // when the page loaded
const url = "Akut.txt";
const whichHeader = "Last-Modified";
const compareTimeToNow = (time) => {
  let d = new Date();
  let diffSec = Math.round((d - time) / 1000);
  document.getElementById("time").textContent = Math.trunc(diffSec / 60) + " minutes"; // time since it was modified
  if ((d - pageload) / 1000 > 10 && diffSec < 5) location.reload();
  else setTimeout(getHeader, 2500)
};

const getHeader = () => {
  const req = new XMLHttpRequest();
  req.addEventListener("load", reqListener);
  req.open("HEAD", url);
  req.send();
};

function reqListener() {
  console.log(this.responseText);
  compareTimeToNow(new Date(this.getResponseHeader(whichHeader)).getTime());
}
getHeader();

使用Fetch(Chrome 42+、Edge 14+、Safari 10.1+Firefox 39+和Opera 29+-无IE)

const pageload = new Date(); // when the page loaded
const url = "Akut.txt";
const whichHeader = "Last-Modified";
const compareTimeToNow = (time) => {
  let d = new Date();
  let diffSec = Math.round((d - time) / 1000);
  document.getElementById("time").textContent = Math.trunc(diffSec / 60) + " minutes"; // time since it was modified
  if ((d - pageload) / 1000 > 10 && diffSec < 5) location.reload();
  else setTimeout(getHeader, 2500)
};

const getHeader = () => {
  fetch(url)
  .then(rsp => compareTimeToNow(new Date(rsp.headers.get(whichHeader)).getTime());
};

getHeader();

Javascript相关问答推荐

一次仅播放一个音频

成帧器运动中的运动组件为何以收件箱开始?

每次子路由重定向都会调用父加载器函数

从PWA中的内部存储读取文件

拖放仅通过 Select 上传

使用下表中所示的值初始化一个二维数组

分层树视图

并不是所有的iframe都被更换

如何解决useState错误—setSelect Image不是函数''

如何在使用rhandsontable生成表时扩展数字输入验证?

连接到游戏的玩家不会在浏览器在线游戏中呈现

有条件重定向到移动子域

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

无法避免UV:flat的插值:非法使用保留字"

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

更改agGRID/Reaction中的单元格格式

P5JS-绘制不重叠的圆

JAVASCRIPT SWITCH CASE语句:当表达式为';ALL';

FindByIdAndUpdate在嵌套对象中创建_id

通过解构/功能组件接收props-prop验证中缺少错误"