Why Use Callbacks?

Why use callbacks?

If you've never seen a callback before, you might be curious why we use them. Consider the following two code examples from a weather app, both of which get the weather from the Internet and show it on the screen.

Example 1, synchronous

var weather = getWeatherFromInternet();
showOnScreen(weather);
checkForFloodWarning();

Example 2, with callbacks

getWeatherFromInternet(function(weather) {
	showOnScreen(weather);
});
checkForFloodWarning();

In the first example, we have to wait for the result of getWeatherFromInternet() before we can check for a flood warning. In the second example, getWeatherFromInternet takes a parameter, a callback function. Instead of waiting for it to return, we just tell it what to do when it's done. This way we can check for a flood warning while getWeatherFromInternet(callback()) is running.