In some places we have to have only one instance of function running.
This code works for me:
function example() {
var that = this;
if(that.running) {
return false;
}
that.running = true;
$.get(url, {}, function (data) {
that.running = false;
});
}
How we can improve it, and make it more reusable?
UPD Here is solution, based on Frits van Campen answer:
function make_run_once(callback) {
callback.running = false;
return function () {
if(callback.running) {
return false;
}
callback.running = true;
deferred = $.Deferred();
deferred.done(function () {
callback.running = false;
});
callback(deferred); // pass deferred to callback so it can resolve at it's own leisure
};
}
You might want to use jQuery’s `Deferred’ functionality for that:
A decorated function will always return the same Deferred object, which will be resolved with the callback from the original function – started on the first invocation.