Skip to content

Instantly share code, notes, and snippets.

@maccman
Last active September 15, 2021 15:45
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save maccman/5944646 to your computer and use it in GitHub Desktop.
Save maccman/5944646 to your computer and use it in GitHub Desktop.
$ = jQuery
TIMEOUT = 20000
lastTime = (new Date()).getTime()
setInterval ->
currentTime = (new Date()).getTime()
# If timeout was paused (ignoring small
# variations) then trigger the 'wake' event
if currentTime > (lastTime + TIMEOUT + 2000)
$(document).wake()
lastTime = currentTime
, TIMEOUT
$.fn.wake = (callback) ->
if typeof callback is 'function'
$(this).on('wake', callback)
else
$(this).trigger('wake', arguments...)
(function($){
var TIMEOUT = 20000;
var lastTime = (new Date()).getTime();
setInterval(function() {
var currentTime = (new Date()).getTime();
if (currentTime > (lastTime + TIMEOUT + 2000)) {
$(document).wake();
}
lastTime = currentTime;
}, TIMEOUT);
$.fn.wake = function(callback) {
if (typeof callback === 'function') {
return $(this).on('wake', callback);
} else {
return $(this).trigger('wake');
}
};
})(jQuery);
@acdha
Copy link

acdha commented Jul 29, 2013

Date.now might be preferable to churning Date instances. It's probably advisable to cache $(document) as well, although it's not called anywhere near as frequently.

I generally also prefer to simplify the math to avoid needing to repeat part of the calculation and bury the slop factor down in the implementation:

var maxDelta = Math.floor(TIMEOUT * 1.1);

if (currentTime - lastTime > maxDelta) {

@guidobouman
Copy link

Good point on the Date.now case: http://jsperf.com/date-now-vs-date-gettime

I prefer the currentTime > (lastTime + TIMEOUT + 2000) notation though. Much more readable.

@rbrcurtis
Copy link

Apparently many browsers will pause setInterval when the browser window isn't focused, whichmeans this will trigger wake any time you focus another window for more than ~22 seconds. or am I misunderstanding something?

http://www.goat1000.com/2011/03/23/how-accurate-is-window.setinterval.html

@vinnymac
Copy link

It appears that some do. Chrome/Firefox limit the setInterval time to around 1000 ms. IE/Safari/Opera have no restrictions. However, according to this that may not be true on iOS. For a more in depth explanation read this StackOverflow Post.

WakeUp is a jQuery library that does the same thing. I recommend combining this with the changes recommended by acdha above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment