Skip to content

Instantly share code, notes, and snippets.

@aungthuoo
Created May 19, 2024 16:01
Show Gist options
  • Save aungthuoo/250a2c6736b59666ebecf3da1a3af668 to your computer and use it in GitHub Desktop.
Save aungthuoo/250a2c6736b59666ebecf3da1a3af668 to your computer and use it in GitHub Desktop.

JavaScript Callback

A JavaScript callback is a function which is to be executed after another function has finished execution.

Simply said:- Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function. This results in callback hell.

// callbacks an callback hell
let fruits = ["apple", "banana", "orange"];

const animateAll = (animate) => {
  // below is the callback hell
  setTimeout(() => {
    animate(fruits[0]);
    setTimeout(() => {
      animate(fruits[1]);
      setTimeout(() => {
        animate(fruits[2]);
      }, 1000);
    }, 1000);
  }, 1000);
};

const animate = (fruit) => {
  console.log("calling", fruit);
};

animateAll(animate);

Output:

calling apple
calling banana
calling orange
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment