Skip to content

Instantly share code, notes, and snippets.

@puyo
Last active October 13, 2015 03:07
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 puyo/51570b9013bb3b30270f to your computer and use it in GitHub Desktop.
Save puyo/51570b9013bb3b30270f to your computer and use it in GitHub Desktop.
// These may *look* like nested conditions but they run at wildly different
// times during your program's execution.
//
// In the example below, t represents the time elapsed since starting the
// code.
//
// The user clicks the button at t = 100.
var condition1 = true;
var condition2 = true;
if (condition1) { // t = 1
var onClick = function() { // t = 2
if (condition2) { // t = 100
$('.output').html("Conditions are met!"); // t = 101
}
}
$('button').on("click", onClick); // t = 3
condition1 = false; // t = 4
}
// So to rearrange these lines of code in order of execution:
// t = 1: if (condition1) { ... }
// t = 2: var onClick = function() { ... }
// t = 3: $('button').on("click", onClick);
// t = 4: condition1 = false;
// t = 100: if (condition2) { ... }
// t = 101: $('.output').html("Conditions are met!"); // but condition1 = false !!!! :(
// Question:
// - How would I write this function so that the output is set ONLY
// when condition1 and condition2 are both true?
// What is the difference between these programs?
// 1
$("button").on("click", alert("Button clicked"));
// 2
var onClick = function() {
alert("Button clicked");
}
$("button").on("click", onClick);
// Question to ask yourself:
// - What *type* of value does the on() method require for its second argument?
// - What is the value being passed into the on() method?
// - Is it a function definition, or the return value from a function call?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment