Callback Function Simple Explaination

Callback Function

A callback function is a function that you pass into another function, so it can be called later when something happens.

Human example:

You order food at a restaurant.

You tell the waiter: “When my food is ready, call me.”

Here, calling you later is like a callback.

In programming:

function cookFood(callback) {
  console.log("Cooking food...");

  callback();
}

function tellCustomer() {
  console.log("Your food is ready!");
}

cookFood(tellCustomer);

Output:

Cooking food...
Your food is ready!

Here, tellCustomer is the callback function.

Because we pass it into cookFood(tellCustomer).

Then cookFood runs it later using callback();

Another common example:

setTimeout(function () {
  console.log("This runs after 2 seconds");
}, 2000);

Here, the function inside setTimeout is a callback. It runs after 2 seconds.

Comments

Popular posts from this blog

How to Check for NVIDIA GPU and Set It Up in Ubuntu

Use the Google Custom Search JSON API to retrieve images

Add linux app to ubuntu