Skip to content

Instantly share code, notes, and snippets.

@zapthedingbat
Created September 30, 2014 09:19
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 zapthedingbat/c0e5b754941d391da8b1 to your computer and use it in GitHub Desktop.
Save zapthedingbat/c0e5b754941d391da8b1 to your computer and use it in GitHub Desktop.
Calling the returned function signals to run the specified function or, if the function is already executing, flag that it should run once more.
function onceMore(f) {
var isWorking = false,
isWaiting = false;
function execute() {
isWaiting = false;
isWorking = true;
f().then(complete);
}
function complete() {
if (isWaiting) {
execute();
} else {
isWorking = false;
}
}
function queue() {
if (isWorking) {
isWaiting = true;
} else {
execute();
}
};
return queue;
}
@zapthedingbat
Copy link
Author

Example Usage

var doStuff = function(){
  return new Promise(function executor(resolve, reject){
    setTimeout(function(){
      // Simulate long running async task
      resolve();
    }, 10000);
  });
}

var doStuffOnceMore = onceMore(doStuff);

doStuffOnceMore();
doStuffOnceMore();
doStuffOnceMore();
doStuffOnceMore();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment