You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

47 lines
1.2 KiB

function adaptiveSetInterval(fn, runNow) {
// unconditionally run every minute
setInterval(fn, 60000);
// scheduleRun() keeps calling fn and decreasing quota
// every 3 seconds, until quota runs out.
var quota = 0;
var scheduledId = null;
function scheduleRun() {
if (quota > 0) {
quota -= 1;
clearTimeout(scheduledId);
scheduledId = setTimeout(scheduleRun, 3000);
fn();
}
}
document.addEventListener("visibilitychange", function() {
if (document.visibilityState == "visible") {
// tab becomes visible: reset quota
if (quota == 0) {
quota = 20;
scheduleRun();
} else {
quota = 20;
}
} else {
// lost visibility, clear quota
quota = 0;
}
});
// user moves mouse: reset quota
document.addEventListener("mousemove", function() {
if (quota == 0) {
quota = 20;
scheduleRun();
} else {
quota = 20;
}
});
if (runNow) {
quota = 20;
scheduleRun();
}
}