Back
LearnJavaScript From ZeroWhy async? setTimeout & callbacks

Why async? setTimeout & callbacks

2 min read

Some things take time

Loading a photo, calling a server, waiting three seconds — these do not finish instantly. If JavaScript froze while waiting, your whole page would hang. So JavaScript does slow tasks asynchronously — it starts them, keeps going, and deals with the result when it is ready.

setTimeout — do something later

The simplest taste of async is setTimeout, which runs code after a delay.

console.log("Start");

setTimeout(() => {
  console.log("3 seconds later");
}, 3000);

console.log("End");

The output is Start, End, then (after 3s) "3 seconds later". Notice "End" prints before the delayed line — JavaScript did not wait. That is async in action.

What is a callback?

A callback is simply a function you hand to another function, to be run later — like the arrow function above. "Call this back when you are done."

function loadData(callback) {
  setTimeout(() => {
    callback("Here is your data");
  }, 1000);
}

loadData((result) => console.log(result));

The problem with callbacks

When you nest many callbacks (one waiting on another waiting on another), the code becomes a messy pyramid — people call it "callback hell". That pain is exactly why Promises were invented, which we learn next.

Async = start slow work, keep going, handle it later. Callbacks were the first tool for it — but they get messy when stacked.

Tip