By setting a timeout you’ve introduced asynchronous behaviour which is similar to what would happen if you replaced your timeout with a network call to a server like you mentioned in another reply.
The callback is simply being called when the timeout finishes or in the network call analogy, when the request returns a response.
JavaScript doesn’t “wait” like you’re assuming. It instead continues on and “callsback” the first function when it’s finished its asynchronous job (a network call or timeout).
To handle that you move the code that you don’t want executed until the execution of the callback inside of the callback. In your case that would mean placing your call to callback()
inside of the other “callback” (the function you’re passing as an argument to setTimeout
. It would look like this:
function one(callback){
setTimeout(function show(){
console.log("one");
callback();
},3000)
}
function two(){
console.log("two");
}
one(two);
The above example will print:
One
Two
If it helps you understand, your code has two callbacks not just one.
Either way, this is the classic way of dealing with asynchronous programming in JavaScript and what I assume you’ve been trying to learn about and understand.
I think it’s a good idea to get a handle on this, but it’s also worth knowing that most apps today don’t deal with asynchronous programming this way anymore.
In later versions of JS (ES6 and beyond) we were given Promises. They allow us to deal with asynchronous behaviour without passing around all these callback functions (known as “callback hell”). Promises is a whole other topic to learn so I won’t explain here but it’s necessary to learn about.
After you understand Promises, the next additions to JS was Generators and Yield. You don’t have to learn about that but it’s worth knowing that the new async/await
syntax is built on top of what Generators and Yield allows us to do which is essentially pause the execution of code while we wait for an asynchronous function to finish it’s work so that our code “looks” like it’s synchronous (running each line one after the other).
And I’d say that most modern applications are being written with the async/await
syntax these days so it’s pretty important to learn.