Created
November 14, 2012 22:25
-
-
Save robcolburn/4075294 to your computer and use it in GitHub Desktop.
Tasking jobs, will catch-up, get back on track
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
function Tasker () { | |
this.tasks = []; | |
this.wait(); | |
} | |
Tasker.prototype = { | |
resolution: 1000, | |
timeoutID: 0, | |
isWaiting: false, | |
tasks: [], | |
add: function (name, perform, interval) { | |
this.tasks.push({ | |
name: name, | |
perform: perform, | |
interval: interval, | |
last: 0 | |
}); | |
}, | |
remove: function (name) { | |
for (var i = 0; i < this.tasks.length; i++) { | |
if (this.tasks[i].name === name) { | |
this.tasks.splice(i, 1); | |
} | |
} | |
}, | |
destroy: function () { | |
if (this.isWaiting) { | |
window.clearTimeout(this.timeoutID); | |
} | |
this.isWaiting = false; | |
this.timeoutID = 0; | |
this.tasks.length = 0; | |
}, | |
run: function () { | |
var now = (new Date()).getTime(); | |
var diff = 0; | |
var i = 0; | |
var task; | |
for (i = 0; i < this.tasks.length; i++) { | |
task = this.tasks[i]; | |
diff = now - task.last; | |
if (diff >= task.interval) { | |
task.perform(diff); | |
task.last = now; | |
} | |
} | |
}, | |
wait: function () { | |
var THIS = this; | |
if (!this.isWaiting) { | |
this.timeoutID = window.setTimeout(function () { | |
THIS.isWaiting = false; | |
THIS.play(); | |
}, this.resolution); | |
this.isWaiting = true; | |
} | |
} | |
}; | |
var tasks = new Tasker(); | |
tasks.add('poll database service', function () { | |
// do that… | |
}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment