Last active
September 1, 2015 11:47
-
-
Save infovore/b6c4bc71a1bffdfd9846 to your computer and use it in GitHub Desktop.
setTimeout is probably the first place you ever used a callback.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's make an alert 2s after a page loads. | |
// We'll need to set a timeout. | |
// What are the ways we can make Timeouts? | |
// This was the way I first learned. | |
function hello() { | |
alert("Hello!"); | |
} | |
setTimeout(hello, 2000); | |
// See that hello there? That's not a string. That's not the name of the function, it's **the function itself**. | |
// Why is that possible? | |
// Well, the above is identical to this: | |
var hello = function() { | |
alert("Hello!"); | |
} | |
setTimeout(hello, 2000); | |
// Functions are objects in Javascript, just like strings, arrays, numbers, and so forth. | |
// All the function keyword does is make a new function object with that name. | |
// So here you can see more clearly what's going on: we're making a function object called hello, and passing that in. | |
// Of course, we don't need to pass in a named object. | |
// We can just make an _anonymous function_ - one with no name, that we define in line. Like so: | |
setTimeout(function() { | |
alert("Hello!"); | |
}, 2000) | |
// We know that 'function' makes a new function object. | |
// So that inline, un-named function definition... just evaluates to a function object. | |
// In all these cases, when 2000ms are up, the first parameter of setTimeout is called. | |
// In all these cases, that first parameter is a function object. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wonder how passing data could be demonstrated in this example... maybe:
// Let's redefine the callback to take a parameter
// Now in the case of setTimeout, you can pass parameters to the callback by adding them like this
// setTimeout(callbackFunction, timeToWait, param1)
// So if we write:
// Our hello function will receive the name "Tom" and will alert the string "Hello Tom!"