JavaScript callbacks

This is the old-fashioned classical approach to asynchronous programming. You provide a function as an argument to another function that executes an asynchronous task, a callback function. When the asynchronous task completes, the executing function calls your callback function.

The main disadvantage of this approach occurs when you have multiple chained asynchronous tasks, which requires you to define callback functions withing callback functions within callback functions. This is called callback hell.

As an example, the setTimeout function, available both in Node.js and in browsers, waits a given number of milliseconds (a second is a thousand milliseconds) and then calls a function.

setTimeout(() => console.log("Tick"), 500);

This style of programming is workable, but the indentation level increases with each asynchronous action because you end up in another function. Doing more complicated things, such as running multiple actions at the same time, can get a little awkward.

setTimeout(() => {
  console.log("Tick 1");
  setTimeout(() => {
    console.log("Tick 2");
    setTimeout(() => {
      console.log("Tick 3");
      setTimeout(() => {
        console.log("Tick 4");
      }, 500);
    }, 500);
  }, 500);
}, 500);