/* * Simple inactivity detector. * When user is inactive for more then 60 sec it is detected * Was written to prevent unnecessary ajax calls when user left * our page open and went for lunch or 2 weeks holidays ;-) * * author Szymon Danielczyk danielczyk.szymon(remove this)@(remove that)gmail.com * * Example of use: * At the begining when you loading your classes * var detector = new IdleDetector(OPTIONS); * where: * OPTIONS.inactivityTimeInSec (optional) - time of inactivity in second after detector set it state to isIdle=true * OPTIONS.idleCallback (optional) - callback function triggered when user is not active and detector detects idle * OPTIONS.backToActivityCallback (optional)- callback function triggered when user become active again * * than later in your code: * if(!detector.isIdle){ * // do ajax request to your server * } * */ function IdleDetector(options){ this.inactivityTimeInSec = 60; //default value this.backToActivityCallback = null; this.idleCallback = null; this.isIdle=false; this.idleTimeout = null; // overwrite options if provided if(options && options.inactivityTimeInSec){ this.inactivityTimeInSec = options.inactivityTimeInSec; } if(options && options.idleCallback){ this.idleCallback = options.idleCallback; } if(options && options.backToActivityCallback){ this.backToActivityCallback = options.backToActivityCallback; } var THIS = this; document.onmousemove = function(e) { THIS.cancelIdle(); }; document.onmousedown = function(e) { THIS.cancelIdle(); }; document.onkeydown = function(e){ THIS.cancelIdle(); }; this.cancelIdle(); } IdleDetector.prototype.setIdle=function(){ this.isIdle=true; if(this.idleCallback){ this.idleCallback(); } }; IdleDetector.prototype.cancelIdle=function(){ if(this.isIdle===true && this.backToActivityCallback){ //set up isIdle to false before call callback this.isIdle=false; this.backToActivityCallback(); } this.isIdle=false; clearTimeout(this.idleTimeout); var THIS = this; this.idleTimeout = setTimeout(function(THIS){THIS.setIdle();},THIS.inactivityTimeInSec*1000,THIS); };