Skip to content

Instantly share code, notes, and snippets.

@oberhamsi
Created October 10, 2012 14:34
Show Gist options
  • Save oberhamsi/3866011 to your computer and use it in GitHub Desktop.
Save oberhamsi/3866011 to your computer and use it in GitHub Desktop.
/*!
* @version 1.0
* @see ORFON
* A setInterval which is pausable and does not trigger
* when the current document doesn't have focus.
*
* Must explictely be `start()`ed.
*
* Optionally, the callback can return `false` in which case the
* `interval` duration is increased in `intervalStep` up to `maxInterval` until a later callback
* returns `true` at which point the `interval` is reset to `minInterval`.
*/
jQuery(function($) {
$.FocusInterval = function(func) {
// const
var minInterval = 10;
var maxInterval = 1800
var intervalStep = 10,
// var
var isPaused = true;
var interval = 10,
var tick = function() {
// if we don't have focus or we are paused -> check again later
if (isPaused || !document.hasFocus()) {
window.setTimeout(tick, minInterval * 1000);
return;
}
var returnValue = options.func();
if (returnValue === false) {
interval = Math.min(interval + intervalStep, maxInterval);
}
if (returnValue === true) {
interval = minInterval;
}
window.setTimeout(tick, interval * 1000);
}
tick();
return {
stop: function() {
isPaused = true;
},
start: function() {
isPaused = false;
},
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment