Created
November 7, 2018 13:16
-
-
Save lucasferreira/c9fb64417403dc675bd0915ee606a760 to your computer and use it in GitHub Desktop.
Absolute setInterval and setTimeout to work in "stand by" tabs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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