Skip to content

Instantly share code, notes, and snippets.

@infovore
Last active September 1, 2015 11:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save infovore/b6c4bc71a1bffdfd9846 to your computer and use it in GitHub Desktop.
Save infovore/b6c4bc71a1bffdfd9846 to your computer and use it in GitHub Desktop.
setTimeout is probably the first place you ever used a callback.
// 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.
@asmt3
Copy link

asmt3 commented May 1, 2015

I wonder how passing data could be demonstrated in this example... maybe:

// Let's redefine the callback to take a parameter

function hello(name) {
   alert("Hello " + name + "!");
}

// 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:

setTimeout(hello, 2000, "Tom");

// Our hello function will receive the name "Tom" and will alert the string "Hello Tom!"

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