UNPKG

idle-state-listener

Version:

JavaScript helper to add users idle state Listener on browser.

1 lines 2.4 kB
function UserStateManager(){var e=null,i=function(){return(new Date).getTime()};this.addListener=function(i,t){var n="state_ts_"+i,r=this;return e||(this.eventManager(),e=[]),e[n]||isNaN(i)?(console.warn("Can't add "+n+" as it is already exist (or) invalid input."),!1):(e[n]={},e[n].duration=i,this.setTimers(i,t),{removeListener:this.removeListener.bind(this,i),reInitiate:function(){r.removeListener.bind(r,i),r.addListener.bind(r,i,t)}})},this.setTimers=function(t,n){var r="state_ts_"+t,s=this;e[r].timer=setTimeout(function(){n(),s.removeListener(e[r].duration)},t),e[r].endTs=t+i(),e[r].cb=n},this.removeListener=function(i){var t="state_ts_"+i;e[t]?(clearTimeout(e[t].timer),delete e[t]):console.warn("state for duration - "+i+" is not avialble to remove")},this.removeAllListeners=function(){for(var i in e)clearTimeout(e[i].timer);e=null},this.eventManager=function(){var e=this;window.onmousemove=function(i){return e.xy==i.clientX+"x"+i.clientY?!0:(e.xy=i.clientX+"x"+i.clientY,void e.resetTimerForActiveUser.call(e))},window.onmousedown=this.resetTimerForActiveUser(this),window.onclick=this.resetTimerForActiveUser.bind(this),window.onscroll=this.resetTimerForActiveUser.bind(this),window.onkeypress=this.resetTimerForActiveUser.bind(this),window.onfocus=this.resetTimeoutONFocus.bind(this),window.onpageshow=this.resetTimeoutONFocus.bind(this),visibleChangeListener.addVisibleChangeListener(this.resetTimeoutONFocus.bind(this))},this.resetTimeoutONFocus=function(){for(var t in e)e[t]&&(e[t].endTs>=i()?(clearTimeout(e[t].timer),this.setTimers(e[t].duration,e[t].cb)):(self.removeListener(e[t].duration),e[t].cb()))},this.resetTimerForActiveUser=function(){for(var t in e)if(e[t]){var n=e[t].duration,r=e[t].cb;e[t].endTs>=i()?(clearTimeout(e[t].timer),this.setTimers(n,r)):(self.removeListener(n),r())}}}var visibleChangeListener=function(){var e,i,t,n={hidden:"visibilitychange",webkitHidden:"webkitvisibilitychange",mozHidden:"mozvisibilitychange",msHidden:"msvisibilitychange"};for(e in n)if(e in document){i=n[e];break}var r=function(e){return e&&document.addEventListener(i,e),!document[i]},s=function(){t&&document.removeEventListener(i,t)};return{addVisibleChangeListener:r,removeVisibleChangeListener:s}}(),stateManager,GetState=function(){return stateManager||(stateManager=new UserStateManager),stateManager};"undefined"!=typeof module&&(module.exports={GetState:GetState});