Callbacks in JavaScript--Beginners Guide

Let us understand in simpler words. What is a callback? A callback which can be called after sending it. So let's now send a function and callback it, so that make it as callback function. This is what it means in layman's terms

Let's get a wrap-around with the help of functions in JavaScript. So here in JS, a function called an argument to another function and return is known as a callback function.

Now let's think in real real-life example — Suppose you are cooking a delicious food that takes some time to finish. Now as you are preparing the food simultaneously you will also arrange the dishes and drinks for the meal. It is not like letting the cooking finish and after that, I will make dishes and drinks ready.

So similarly JavaScript is a single-threaded programming language sometimes also called a Synchronous programming language. This means everything runs step by step, like first making the Food →Arrange dishes →Drinks. So this is a consuming process. In order to overcome this single-threaded/Synchronous process callback functions are introduced.

So callback functions are introduced to make JavacSript as Asynchronous programming language. Let us understand the callbacks more programmatically way.

function food(rice){
    console.log("Food is getting prepared");
    setTimeout(function(){
        rice();
     },5000);
    console.log("Dishes and Drinks are ready");
 }

 function rice(){
 console.log("food is ready");
 }
 food(rice);

Now let us understand what actually is happening here. As we see function food is higher-order function, because inside the food we are using function rice to be called back after some time. As we already know that JavaScript is asynchronous, so it wont wait until the food is ready, so what it will do it is it will jump to make “Dishes and Drinks ready”, so after that our “food will be ready”.

In order to make JS async we are using setTimeout()function and purposely we are delaying our time for 5 seconds, meanwhile we can arrange other things. So in real-time example, while sending the api calls or retrieving the data from the servers, this setTimeout(async) will be helpful to run smoothly

setTimeout() take a callback function as an argument and execute the callback function after a specified amount of time.

It takes two arguments: the first is the callback function to be executed, and the second is the time delay in milliseconds before the callback is invoked.

In the given example, if you have a setTimeout() set to 5000 milliseconds (or 5second), it means that the provided callback function will be executed after 5 seconds.