title: Plain JS countdown with repeat and delay
body: <p>I keep running into several issues when creating a countdown script</p>
  
  <ol>
  <li>it does not run smoothly</li>
  <li>hard to make it repeat (closure)</li>
  <li>hard to delay the start and to delay the repeat (closure)</li>
  </ol>
  
  <p>Can someone please help me FIX this code which should work in my opinion but doesn't</p>
  
  <p>the processing I need is </p>
  
  <p>a. counter starts <em>delay</em> number of seconds after the page loads,<br>
  b. when counter reaches 0, the countdown RE-starts after <em>delay</em> number of seconds   </p>
  
  <p><a href="http://jsfiddle.net/mplungjan/RVBDQ/" rel="nofollow">Here is my Fiddle</a></p>
  
  <p>Issues:</p>
  
  <ol>
  <li>when it starts, the counter seems to wait an additional second before counting down</li>
  <li>it does not pause </li>
  <li>the repeat starts after the counter has continued</li>
  </ol>
  
  <p>.</p>
  
  <pre><code>// more accurate timer - https://gist.github.com/1185904
  function interval(duration, fn){
    this.baseline = undefined
  
    this.run = function(){
      if(this.baseline === undefined){
        this.baseline = new Date().getTime()
      }
      fn()
      var end = new Date().getTime()
      this.baseline += duration
  
      var nextTick = duration - (end - this.baseline)
      if(nextTick&lt;0){
        nextTick = 0
      }
      (function(i){
          i.timer = setTimeout(function(){
          i.run(end)
        }, nextTick)
      }(this))
    }
  
    this.stop = function(){
     clearTimeout(this.timer)
    }
  }
  window.onload=function() {
    var cnt1 = 10;
    var delay1 = 5;
    var timer1 = new interval(1000, function(){
      document.getElementById('out1').innerHTML=cnt1--
      if (cnt1 &lt;= 0) { // trying to reset
        timer1.stop(); // does not work
        cnt1 = 10;
        setTimeout(function() { timer1.run()},delay1*1000)
      }
    })
    setTimeout(function() { timer1.run()},delay1*1000)
  }  
  </code></pre>