Created
June 6, 2011 15:50
-
-
Save robink/1010508 to your computer and use it in GitHub Desktop.
Javascript Deferred Interval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var delayedTimeout = function( callback, initialTime, maxTime ) { | |
this.currentTime = initialTime; | |
this.callback = callback; | |
this.maxTime = 0 || maxTime; | |
this.nextTick(); | |
} | |
delayedTimeout.prototype = { | |
stop : function () { | |
this.stopNext = true; | |
}, | |
nextTick : function() { | |
if ( this.stopNext ) | |
return; | |
if ( ! this.previousTime ) | |
this.previousTime = 0; | |
var newTime = this.previousTime + this.currentTime; | |
this.previousTime = this.currentTime; | |
this.currentTime = newTime; | |
if ( newTime > this.maxTime ) | |
newTime = this.maxTime; | |
var that = this; | |
this.timeout = setTimeout(function() { that.onTimeout( that ) } , newTime); | |
}, | |
onTimeout : function( ctx ) { | |
var that = this; | |
if ( ctx ) | |
that = ctx; | |
that.callback(); | |
that.nextTick(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Of course, this sample is intended to be run with nodejs.