Skip to content

Instantly share code, notes, and snippets.

@shmup
Forked from thischarmingsam8/IdleTimer.coffee
Created August 19, 2014 19:13
Show Gist options
  • Save shmup/b358eb6d75c6b46ae83e to your computer and use it in GitHub Desktop.
Save shmup/b358eb6d75c6b46ae83e to your computer and use it in GitHub Desktop.
0
class window.IdleTimer
constructor: () ->
@timer
@timeIncrement = 1000
@timeIdle = 0
@timeMax = 10000
@expired = false
@interactionMethods = ['click','mousemove']
# these should not be in here. move somewhere else.
@expiryCallback = () -> console.log 'expiry callback'
@tickCallback = () -> console.log 'tick callback'
@awakeCallback = () -> console.log 'awake callback'
if document.documentElement.hasOwnProperty('ontouchmove')
@interactionMethods.push('touchmove')
start: () ->
@timeIdle = 0
@timer = setInterval (=> @checkIdleTime()), @timeIncrement
for method in @interactionMethods
document.addEventListener(method, => @resetTimer())
stop:() ->
clearInterval(@timer)
for method in @interactionMethods
document.removeEventListener(method, => @resetTimer())
checkIdleTime: () ->
@timeIdle += @timeIncrement
if typeof @tickCallback is 'function' and @timeIdle <= @timeMax
@tickCallback()
if @expired is off and @timeIdle > @timeMax
@expired = on
if typeof @expiryCallback is 'function'
@expiryCallback()
resetTimer:() ->
if @expired is on
@expired = off
if typeof @awakeCallback is 'function'
@awakeCallback()
@timeIdle = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment