Skip to content

Instantly share code, notes, and snippets.

@zeekay
Last active August 29, 2015 14:04
Show Gist options
  • Save zeekay/80e3bf54221e997f42a3 to your computer and use it in GitHub Desktop.
Save zeekay/80e3bf54221e997f42a3 to your computer and use it in GitHub Desktop.
// Lock async function until complete.
function lock(fn) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
var cb = args.pop() || function(){};
var that = this;
if (fn.locked)
return cb(new Error('locked!'))
args.push(function() {
fn.locked = false;
cb.apply(that, arguments);
})
fn.locked = true;
fn.apply(that, args);
}
}
// Calls back with 'unlocked!' if there is no error.
var lockedFn = lock(function(cb) {
setTimeout(function() {
cb(null, 'unlocked!')
}, 100)
})
// Our generic callback
function complete(err, res) {
if (err)
console.log('locked!')
else
console.log(res)
}
// Try to run multiple times!
lockedFn(complete)
lockedFn(complete)
lockedFn(complete)
// Wait til unlocked again
setTimeout(function() {
lockedFn(complete)
}, 200)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment