Created
January 28, 2010 07:56
-
-
Save yoko/288540 to your computer and use it in GitHub Desktop.
setInterval controller
This file contains 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 Cycle = function(interval) { | |
if (interval) this.interval = interval; | |
}; | |
Cycle.prototype = { | |
queue : null, | |
timer : null, | |
interval : 500, | |
start_time: 0, | |
start: function() { | |
var self = this; | |
this.stop(); | |
this.start_time = +(new Date); | |
this.timer = setInterval(function() { | |
for (var i = 0, l = self.queue.length; i < l; i++) { | |
var q = self.queue[i]; | |
if (!q) continue; | |
var method = q.method; | |
if (typeof method != 'function') this.remove(i); | |
else { | |
q.times = (q.times ? q.times++ : 1); | |
q.progress = +(new Date) - self.start_time; | |
method(q.times, q.progress); | |
} | |
} | |
}, this.interval); | |
}, | |
stop: function() { | |
clearInterval(this.timer); | |
}, | |
add: function(q) { | |
if (!this.queue) this.queue = []; | |
if (typeof q == 'function') q = { method: q }; | |
this.queue.push(q); | |
return this.queue.length - 1; | |
}, | |
remove: function(n) { | |
if (!this.queue) return; | |
if (typeof n == 'function') { | |
var f = n; | |
n = -1; | |
for (var i = 0, l = this.queue.length; i < l; i++) { | |
var q = this.queue[i]; | |
if (f === q.method) { | |
n = i; | |
break; | |
} | |
} | |
} | |
delete this.queue[n]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment