Skip to content

Instantly share code, notes, and snippets.

@Colt
Last active December 28, 2015 21:49
Show Gist options
  • Save Colt/7567442 to your computer and use it in GitHub Desktop.
Save Colt/7567442 to your computer and use it in GitHub Desktop.
Colt's Lesson Plan

Lab/Homework 11/19/13

Design and deliver a lesson on JS callbacks

Today's assignment is to prepare a lesson on callbacks in Javascript. You should assume your students have a basic understanding of JS syntax, variables and functions but have never encountered an asynchronous function and have never heard the word 'callback'.

We suggest you cover the following topics in order:

  • First-class functions

    1. JS treats function as first class objects, which means that it supports creating new functions as a program runs, storing them in data structures, passing them as arguments to other functions, and returning them as values
    • Basically treats functions as variables

    • They're just a special type of object that can do all the things regular objects can do.

    • Function is an instance of the Object Type:

        function feedCat(){
        	alert("Kibble, tinned food and water");
        }
        alert(feedCat instanceof Object);
      
    • You can store the function in a variable:

        function feedCat(){
        	alert("Kibble, tinned food and water");
        }
        var eveningChore = feedCat;
        eveningChore();
      
    • You can pass a function as a paramater to another function:

        function doEveningChores(chores){
        	for(var x=0; x<chores .length; x++)
        	chores[x]();
        }
        doEveningChores([feedCat]);
      
    • You can return a function from a function:

        function tonightChores(){
        	return feedCat;
        }
        var tonight = tonightChores();
        tonight();
      
  • Show that an anonymous function assigned to a variable and a named function are identical

    • An anonymous function is basically a function without a name

      • When you call function(){} it's returning a function object that is invoked and the body is executed
    • For Example:

        function foo(msg){
        	alert(msg);
        }
      
    • Is the same as:

        var foo = function (msg) {
        	alert(msg);
        }
      
  • Show that functions can call other functions

    • Functions can be nested inside eachother and can call other functions.

      • Variables in the local environment are only available to the code inside the function.
    • If a function calls another function, the newly called function does not see the variables inside the first function. So, in this case:

        var variable = "top-level";
      
        function printVariable() {
        	console.log("inside printVariable, the variable holds '" + 
        	variable + "'.");
        }
      
        function test() {
        	var variable = "local";
        	console.log("inside test, the variable holds '" + variable + "'.");
        	printVariable();
        }
      
        test();
      
    • The output of this example is:

        "inside test, the variable holds 'local'."
        "inside printVariable, the variable holds 'top-level'."
      
    • However, if a function is defined inside of another function, it will have access to the variables of its parent function

  • Show that functions can be passed into other functions and called

    • You can pass a function as paramter of another function:

        function doEveningChores(chores){
        	for(var x=0; x<chores .length; x++)
        	chores[x]();
        }
        doEveningChores([feedCat]);
      
  • Introduce asynchronous functions (setTimeout, $.Ajax, whatever you want)

    • Javascript is always synchronous and single-threaded, meaning that if a block of code on a page is executing, then no other Javascript on the page will currently be executed

    • Asynchronous events can handle asynchronous events like timers or mouseclicks or ajax calls

    • Ajax calls - the code will stop executing until the call returns (success or error) at which point the callback will then run synchronously. No other code will be running at this point. It won't interrupt any other code that is running.

Introduce asynchronous functions (setTimeout, $.Ajax, whatever you want) * * Javascript is always synchronous and single-threaded, meaning that if a block of code on a page is executing, then no other Javascript on the page will currently be executed * Asynchronous events can handle asynchronous events like timers or mouseclicks or ajax calls. It's good for events that you might not know when they'll happen. * * Ajax calls - the code will stop executing??? until the call returns (success or error) at which point the callback will then run synchronously. No other code will be running at this point. It won't interrupt any other code that is running. * In AJAX, you can set "async: false", but this can be problematic in that it will block all JS on the page until it finishes. * Calling Javascript asynchronous is sort of misleading. It's more accurate to say that it is synchronous with various callbacks

Javascript's most basic async functions are setTimeout and setInterval.
setTimeout executes a given function after a certain amount of time passes. It accepts a callback function as the first argument and a time (in ms) as the second argument.

	console.log( "a" );
	setTimeout(function() {
		console.log( "c" )
	}, 500 );
	setTimeout(function() {
		console.log( "d" )
	}, 500 );
	setTimeout(function() {
		console.log( "e" )
	}, 500 );
	console.log( "b" );

The console outputs "a", "b", and then 500ms later, "c", "d", and "e". A timeout will not execute until all of the code in a block has executed. So if a timeout is set and then a long running function executes, the timeout won't even start until that long function has finished.

Async functions like setTimeout are pushed onto a queue of callback functions known as the event loop. When an async function executes, the callback function is pushed into the queue. JS doesn't start processing the event loop until the code after an async function has executed.

So, what is a callback? Callbacks are functions that are executed asynchronously. They're just code that gets executed at a later time. Instead of code reading top to bottom procedurally, async programs may execute different functions are different times based on the order and speed that earlier functions like http requests or mouse clicks happen. You use them when you don't know when something will execute, but you do know where they will complete - the last line of the async function!

Callbacks are like the numbers at the bottom of your receipt when you order a hamburger. It tells the restaurant worker what to do when you food is done.

For instance:

$('#element').fadeIn('slow', function() {  
    // callback function 
});  

fadeIn() accepts the speed of the fade-in and an optional callback function. When the fadeIn() method is completed, then the callback function will be executed.

To make a custom callback:

function mySandwich(param1, param2, callback) { 
	alert('Started eating my sandwich. It has: ' + param1 + ', ' + param2);
    callback(); 
} 
mySandwich('ham', 'cheese', function() { 
	alert('Finished eating my sandwich.'); 
});

A More Fleshed Out Version:

function mySandwich(param1, param2, callback) { 
	alert('Started eating my sandwich. It has: ' + param1 + ', ' + param2); 
	$('#sandwich').animate({ 
    	opacity: 0 
	}, 5000, function() { 
    // Animation complete.
	}); 
		if (callback && typeof(callback) === "function") { 
    		callback(); 
		} 
	} 
	mySandwich('ham', 'cheese', function() { 
	alert('Finished eating my sandwich.'); 
	});
@featherart
Copy link

Looks good Colt!
There are a few typos that I think you didn't intend. For ex:
'Asynchronous events can handle asynchronous events like timers or mouseclicks or ajax calls.'
Do you mean asynchronous functions can handle async events?

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