Last active
December 16, 2015 07:09
-
-
Save mbrevoort/5396410 to your computer and use it in GitHub Desktop.
Simple browser IsActive - periodically emit if a user is active or still active, emit if inactive.
This file contains 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
// var isActive = new IsActive(10000, window); | |
// isActive.on('active', function () { console.log('active') }); | |
// isActive.on('inactive', function () { console.log('inactive') }); | |
// isActive.start(); | |
var IsActive = function (timerPeriod, g) { | |
timerPeriod = parseInt(timerPeriod) || 60000; | |
if (!g) g = window; | |
var ACTIVE = true, | |
INACTIVE = false, | |
state = INACTIVE, | |
lastActiveTime = 0, | |
interval = null, | |
self = this; | |
var detectActive = function () { | |
lastActiveTime = Date.now(); | |
if (state === INACTIVE) { | |
markActive(); | |
resetInterval(); | |
} | |
} | |
var markActive = function () { | |
self.emit('active'); | |
state = ACTIVE; | |
} | |
var resetInterval = function () { | |
clearInterval(interval); | |
interval = setInterval(function() { | |
if (lastActiveTime > (Date.now() - timerPeriod)) | |
markActive(); | |
else { | |
if (state === ACTIVE) | |
self.emit('inactive'); | |
state = INACTIVE; | |
} | |
}, timerPeriod); | |
} | |
this.start = function () { | |
g.document.onclick = detectActive; | |
g.document.onmousemove = detectActive; | |
g.document.onkeypress = detectActive; | |
detectActive(); | |
} | |
self._events = {}; | |
self.on = function(event, fct){ | |
self._events[event] = self._events[event] || []; | |
self._events[event].push(fct); | |
} | |
self.emit = function(event /* , args... */){ | |
if(!self._events[event]) return; | |
for(var i = 0; i < self._events[event].length; i++){ | |
self._events[event][i].apply(self, Array.prototype.slice.call(arguments, 1)); | |
} | |
} | |
}; | |
// export in common js | |
if( typeof module !== "undefined" && ('exports' in module)){ | |
module.exports = IsActive; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
what about scroll?