public
Last active

  • Download Gist
jquery.wake.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
$ = 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...)
jquery.wake.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
(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);

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) {

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.