Skip to content

Instantly share code, notes, and snippets.

@lucasferreira
Created November 7, 2018 13:16
Show Gist options
  • Save lucasferreira/c9fb64417403dc675bd0915ee606a760 to your computer and use it in GitHub Desktop.
Save lucasferreira/c9fb64417403dc675bd0915ee606a760 to your computer and use it in GitHub Desktop.
Absolute setInterval and setTimeout to work in "stand by" tabs
function absoluteSetInterval(fn, millis) {
try {
var baseTime = Date.now();
var callHandler = function() {
if (Date.now() - baseTime > millis) {
baseTime = Date.now();
fn();
}
};
return {
_id: window.setInterval(callHandler.bind(this), 10),
type: "interval",
absolute: true
};
} catch (ex) {
return {
_id: window.setInterval(fn, millis),
type: "interval",
absolute: false
};
}
}
function absoluteClearInterval(timer) {
return window.clearInterval(timer._id || timer);
}
function absoluteSetTimeout(fn, millis) {
try {
var _id;
var baseTime = Date.now();
var callHandler = function () {
if (Date.now() - baseTime > millis) {
baseTime = Date.now();
fn();
if(!!_id) window.clearInterval(_id);
}
};
_id = window.setInterval(callHandler.bind(this), 10);
return {
_id: _id,
type: "interval",
absolute: true
};
} catch (ex) {
return {
_id: window.setTimeout(fn, millis),
type: "timeout",
absolute: false
};
}
}
function absoluteClearTimeout(timer) {
if(typeof timer === "object" && timer.type === "interval") {
return absoluteClearInterval(timer);
}
return window.clearTimeout(timer._id || timer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment