Callback functions
Let's take a look and try to write some asynchronous operations with our latest game of thrones example.
Some of the commonest async operations that are provided by the browser is the setTimeout and the setInterval function. We will use the latest GoT example to change the ruler of westeros asynchronously after 5 seconds (yes the battle didn't last long!) from 'Cersei' to 'Danny'.
This is exactly what we did on the code above, but it doesn't seem to work. Why?
Well, because as we explained in the event loop, we may call the function in line 38, but this function contains an asynchronous operation, the setTimeout function. The setTimeout has a callback function inside of it. This callback is the piece of code that will be executed after 5 seconds. But UNTIL then, the ruler will remain 'Cersei Lannister'! And because setTimeout is asynchronous function passes the torch to the next piece of code in this case line 39. That prints the ruler. But the ruler now is Cersei! It will be danny AFTER 5 seconds and only if there is no other code left that the browser is dealing with!
So in order to print the danny message after 5 seconds we need to do it inside the callback function! Don't forget this callback contains the code that will be executed after 5 secs!