Skip to content

Instantly share code, notes, and snippets.

@gschoppe
Last active January 24, 2021 19:43
Show Gist options
  • Save gschoppe/5666cd6ebe527bc00e108d2605e4dafb to your computer and use it in GitHub Desktop.
Save gschoppe/5666cd6ebe527bc00e108d2605e4dafb to your computer and use it in GitHub Desktop.
Class to simplify management of intervals
function IntervalManager() {
this.intervals = [];
// Public
this.setInterval = function(callback, interval, name) {
if (!name) {
name = "" + Date.now() + "|" + Math.random();
}
var newInterval = {
'name': name,
'callback': callback,
'interval': interval,
'enabled' : true,
'lastRun' : 0
};
for(var i = 0; i < this.intervals.length; i++) {
if (this.intervals[i].name == name) {
this.intervals[i] = newInterval;
return;
}
}
this.intervals.arrayPush(newInterval);
};
this.clearInterval = function(name) {
if (!name) {
return false;
}
var startLen = this.intervals.length;
this.intervals = this.intervals.filter(function(obj) {
return obj.name != name;
});
if (startLen > this.intervals.length) {
return true;
}
return false;
};
this.enableInterval = function(name) {
var changed = 0;
for (var i = 0; i < this.intervals.length; i++) {
if (!name || this.intervals[i].name == name) {
this.intervals[i].enabled = true;
if (name) {
return true;
} else {
changed++;
}
}
}
if (changed) {
return true;
}
return false;
};
this.disableInterval = function(name) {
var changed = 0;
for (var i = 0; i < this.intervals.length; i++) {
if (!name || this.intervals[i].name == name) {
this.intervals[i].enabled = false;
if (name) {
return true;
} else {
changed++;
}
}
}
if (changed) {
return true;
}
return false;
};
// Private
this.loop = function() {
var tick = Date.now();
for (var i = 0; i < this.intervals.length; i++) {
if (!this.intervals[i].enabled) {
continue;
}
if (tick - this.intervals[i].lastRun > this.intervals[i].interval) {
this.intervals[i].callback();
this.intervals[i].lastRun = tick;
}
}
setTimeout(function(that) {
that.loop();
}, 1000, this);
};
this.loop();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment