Skip to content

Instantly share code, notes, and snippets.

@yoko
Created January 28, 2010 07:56
Show Gist options
  • Save yoko/288540 to your computer and use it in GitHub Desktop.
Save yoko/288540 to your computer and use it in GitHub Desktop.
setInterval controller
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