bloqhead of Big Sea
12/19/2014 - 2:57 PM

simple Timer class written in coffee script

simple Timer class written in coffee script

class window.Timer
  
  ref : null
  callback : null

  constructor: ( @frequency, @callback, @running = yes ) ->
    @start() if @running

  start: ->
    @stop() if @ref isnt null
    @ref = setInterval( @tick, @frequency )
    @timerStart = new Date()

  progress: ->
    refDate = if @paused then @pauseTime else new Date()
    ( ( refDate.getTime() - @timerStart.getTime() ) % @frequency ) / ( @frequency * 1.0 )

  stop: ->
    if @ref isnt null
      clearInterval @ref
      @ref = null

  pause: ->
    @paused = yes
    @pauseTime = new Date()

  continue: ->
    @paused = no
    @start() if @ref is null

  tick: => @callback(@) if not @paused