Skip to content

Instantly share code, notes, and snippets.

@domfarolino
Created September 23, 2016 20:32
Show Gist options
  • Save domfarolino/780a003633aacbef3d9929343a1720ed to your computer and use it in GitHub Desktop.
Save domfarolino/780a003633aacbef3d9929343a1720ed to your computer and use it in GitHub Desktop.
3rd example explaining closures to Pat
var stopWatchBuilder = function() {
var outerFunctionState = Date.now();
var innerFunction = function() {
console.log("Time difference: " + (Date.now() - outerFunctionState)/1000);
}
return innerFunction;
}
var timer = stopWatchBuilder();
// Next to no time at all from when we generateFunction1 and call it
timer();
// Artificial time delay
for (var i = 0; i < 1000000000; ++i) {}
for (var i = 0; i < 1000000000; ++i) {}
for (var i = 0; i < 1000000000; ++i) {}
// But when we call it later we get the difference of the current time
// and the outerFunctionState which is the time when we first generated
// the function
timer();
for (var i = 0; i < 1000000000; ++i) {}
for (var i = 0; i < 1000000000; ++i) {}
// Again!
timer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment