Skip to content

Instantly share code, notes, and snippets.

@cary929
Forked from manast/interval.js
Created May 13, 2016 08:23
Show Gist options
  • Save cary929/c450f64da17ab33a245e11a43ed03425 to your computer and use it in GitHub Desktop.
Save cary929/c450f64da17ab33a245e11a43ed03425 to your computer and use it in GitHub Desktop.

Revisions

  1. @manast manast created this gist Sep 1, 2011.
    27 changes: 27 additions & 0 deletions interval.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    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<0){
    nextTick = 0
    }
    (function(i){
    i.timer = setTimeout(function(){
    i.run(end)
    }, nextTick)
    }(this))
    }

    this.stop = function(){
    clearTimeout(this.timer)
    }
    }