Simple Job Class (setInterval)
Creates A simple class that encapsulates a long running job with an interval that can be started and stopped.
by Josh Carroll
HTML
<button type="button" id="btnStart">Start</button>
<button type="button" id="btnStop">Stop</button>
<div id="output">Nothing Yet</div>
JavaScript
(function() {
function Job(workUnit, interval) {
this.workUnit = workUnit;
this.interval = interval;
this.id = -1;
}
Job.prototype.start = function() {
if (this.id === -1) {
this.id = window.setInterval(this.workUnit, this.interval);
}
};
Job.prototype.stop = function() {
if (this.id !== -1) {
window.clearInterval(this.id);
this.id = -1;
}
};
var i = 0,
myJob = new Job(function() {
i++;
$("#output").text(i);
}, 100);
$("#btnStart").on("click", function() {
myJob.start();
});
$("#btnStop").on("click", function() {
myJob.stop();
});
}());