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.
What can I do to make this asynchronous?
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check 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?