Skip to content

Instantly share code, notes, and snippets.

@webjay
Created October 9, 2011 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webjay/1274105 to your computer and use it in GitHub Desktop.
Save webjay/1274105 to your computer and use it in GitHub Desktop.
A JavaScript singleton object to handle asynchronous jobs.
/**
* A JavaScript singleton object to handle asynchronous jobs.
* Give it a callback to i.e. know when to close the database connection.
* @author Jacob Friis Saxberg
*/
module.exports = new function () {
this.debug = true;
var jobs = 0;
var done = false;
var callback = null;
function callable () {
if (done && jobs == 0 && callback != null) {
callback();
}
}
/**
* @param functionName The function to call when all jobs are done
*/
this.setCallback = function (functionName) {
if (typeof(functionName) != 'function') {
console.error('callback must be a function');
return false;
}
callback = functionName;
}
/**
* Call this when all jobs have been started.
*/
this.done = function () {
if (this.debug) {
console.log('Jobs done');
}
done = true;
callable();
}
/**
* Call this when a job starts.
*/
this.start = function () {
jobs++;
if (this.debug) {
console.log('Job start ' + jobs);
}
}
/**
* Call this when a job ends.
*/
this.end = function () {
jobs--;
if (this.debug) {
console.log('Job end');
}
callable();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment