Mithril Timer

HTML

<script src="//cdn.rawgit.com/mweststrate/mobservable/master/dist/mobservable.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mithril/0.2.2-rc.1/mithril.min.js"></script>
<div id="app"></div>

CSS

.active{color: darkgreen;}
.inactive{color: black;}
.stopped{color: red;}

CoffeeScript

# http://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss
tdur = (s1) ->
  h1 = Math.floor(s1 / (60 * 60))
  s1 %= 60 * 60
  m1 = Math.floor(s1 / 60)
  s1 %= 60
  h2 = if h1 then h1 + ':' else ''
  m2 = if h1 and m1 < 10 then '0' + m1 else m1
  s2 = if s1 < 10 then '0' + s1 else s1
  h2 + m2 + ':' + s2
  
Timer = 
  controller: (props) ->
    time = m.prop(props.time)
    startTimer = (e) =>
      @timer = setInterval (-> 
        cls('active')
        if (time)() is 0) 
          cls('inactive')
          clearInterval(@timer)
        else 
          time(time() - 1)
        m.redraw()
      , 1000
    stopTimer = (e) => cls('stopped'); clearInterval(@timer)
    resetTimer = (e) => 
      stopTimer(); cls('inactive');
      time(props.time)
    cls = m.prop('inactive')
    {time, startTimer, stopTimer, resetTimer, cls}
  view: (ctrl, props) ->
    m 'div.timer',
      m 'h1', {class: ctrl.cls()}, tdur(ctrl.time()),
        m('br'), ['start', 'stop', 'reset'].map (d) ->
          m 'button', {onclick: ctrl[d + "Timer"]}, d
        
m.mount(
  document.body,
  m Timer, {time: 20}
)