Skip to content

Instantly share code, notes, and snippets.

@jkwok91
Forked from nmalkin/barrier.js
Last active August 29, 2015 14:03
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 jkwok91/883c1012230602071b8e to your computer and use it in GitHub Desktop.
Save jkwok91/883c1012230602071b8e to your computer and use it in GitHub Desktop.
this is a thing nathan wrote. here is what i think this means
"use strict";
/*
this is for simulating a 3 second request? response? a thing that takes 3 seconds to respond
*/
function longRunningFunction1(onComplete) {
setTimeout(onComplete, 3000); // it takes a callback function that it will execute after 3 seconds
}
/*
ditto, for 2 seconds
*/
function longRunningFunction2(onComplete) {
setTimeout(onComplete, 2000);
}
/*
this was the solution i gave where one of the requests made the other request in its callback fn
*/
function executeSequentially() {
longRunningFunction1(function() {
longRunningFunction2(function() {
console.log("The functions running sequentially have finished.");
});
});
}
/*
this is something different
here is a function that takes a callback function. it has a flag to see when a thing called firstFinished is finished.
it also uses a variable called barrier to hold firstFinished, i think.
barrier is returned to be used elsewhere. it is still holding firstFinished, and also callback fn.
at the time of returning/creation of barrier, firstFinished is still false.
the purpose of barrier is to share the variable firstFinished. When firstFinished is finished, the callback function is executed.
*/
function makeBarrier(onComplete) {
var firstFinished = false;
var barrier = function() { // called by each function when it finishes
if(! firstFinished) { // first (by time) function finished
firstFinished = true;
} else { // second function finished
onComplete();
}
};
return barrier;
}
/*
the callback function passed to makeBarrier and to be stored in this variable barrier is a console.log
barrier is then passed to 3second request.
barrier is also passed to 2second request.
since 2second request finishes first (this is arbitrary. the point is that whichever one finishes first will set the firstFinished to true),
it sets firstFinished to true, allowing the 3second request to use barrier to execute callback because firstFinished is now true
*/
function executeSimultaneously() {
var barrier = makeBarrier(function() {
console.log("The functions running simultaneously have finished.");
});
longRunningFunction1(barrier);
longRunningFunction2(barrier);
}
executeSequentially();
executeSimultaneously();
// timer
function timer(i) {
console.log(i);
if(i < 5) setTimeout(function() { timer(i+1); }, 1000);
}
timer(1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment