I have a function that looks through a given page’s DOM for a string. If it finds it, it reloads a page after a randomized amount of seconds have passed. If it doesn’t find the given string, the page stops refreshing.
The function is the following:
function reloadPage() {
const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
const LookFor = "test string";
const interval = getRandomNumber(0, 2);
const intervalHandle = setInterval(function () {
if($('body:contains("' + LookFor + '")').length > 0) {
clearInterval(intervalHandle); // Or else it tries to reload when it's already reloading
window.location.reload();
} else {
clearInterval(intervalHandle);
}
}, interval *1000);
};
It works well enough when the page the code is getting executed on is focused, but when the page isn’t focused, it can take many times over the expected window of time for the refresh to happen. On average, I get a page refresh every 1.29 seconds when the window is focused, and ~15 seconds when the page isn’t focused. Sometimes, it’ll even refresh as soon as I focus back on the page the code is getting run in.
I saw on this answer that JS interval handles go slower on inactive pages for browser performance reasons. Is there a way to make the page always refresh at the set time interval, between 0-2 seconds, regardless of page focus?