TapCub is live — analytics, insights and live chat, free on one platform
Glossary

What is a callback? Meaning, sync vs async and examples

A callback is a function you pass to other code so it can be called later. Synchronous and asynchronous callbacks, the output order that surprises beginners, and a timing example comparing nested and parallel calls.

Su He Reviewed by Ethan Brooks Also called callback function Last updated Nov 19, 2026 Glossary

Quick answer

A callback is a function passed into other code so that the other code can call it later, when an event happens or a task finishes. It is the basic building block of event handlers and asynchronous code, including SDK error and consent hooks.

What a callback is

A callback is a function you pass to other code so that the other code can call it later, when something has happened. MDN defines a callback function as a function passed into another function as an argument, which is then invoked to complete some kind of action (MDN). The name says it: you hand over a function and the other side "calls back" when it is ready.

function greet(name, done) {
  console.log('Hello, ' + name);
  done();               // the callback
}
greet('Ada', function () { console.log('finished'); });

You give up control of when your function runs. That one fact explains most of the surprises people have with callbacks, and the rest of this page is about those surprises.

Outside programming, "callback" has other meanings: a second phone call to someone, a second-round audition, a joke that refers to an earlier one. This page is about the programming meaning.

Synchronous and asynchronous callbacks

MDN separates callbacks by when they run: synchronously (immediately, inside the call) or asynchronously (later, after the current code has finished). Timing matters when you reason about side effects.

KindWhen it runsExamples in JavaScript
SynchronousBefore the calling function returnsArray.prototype.map(), forEach(), sort() comparator
AsynchronousAfter the current code finishes, when an event or timer firessetTimeout(), event listeners, network requests, Promise.then()

A quick check of the difference, with the output in order:

console.log('A');
setTimeout(function () { console.log('B'); }, 0);
[1].forEach(function () { console.log('C'); });
console.log('D');
// A, C, D, B

forEach runs its callback at once, so C comes before D. The timer callback waits until the current code is done, so B comes last even with a zero delay.

Where callbacks are used

  • Event handling. "When this button is clicked, run this function." The handler is a callback.
  • Asynchronous work. Reading a file, a network request or a timer calls your function when the result is ready.
  • Customising a general function. Sorting with your own comparison, or filtering with your own test.
  • Reporting back from a library. An SDK calls your function when it succeeds, fails or changes state.

The same shape works in many languages: C passes function pointers, Python passes functions, Java passes interface objects or lambdas.

Know exactly which arguments the other side passes. The caller supplies them, and the callback only receives what is sent. array.map(function (item, index, array) { ... }) passes the element, its position and the whole array, in that order; a callback that expects them in another order silently misbehaves. Read the documentation of the function you are handing yours to, and write down the order in a comment if you are the one calling.

The conventions that prevent most bugs

  1. Error-first order. Many APIs call callback(error, result): check error first, and only use result when there is none. It makes failure impossible to forget.
  2. Call it once. A callback that can fire twice (once on success, once on a later failure) causes duplicate work.
  3. Always sync or always async. A function that sometimes calls back immediately and sometimes later is hard to reason about; pick one.
  4. Keep your own context. The callback may run with a different this or after variables changed; capture what you need.
  5. Handle failure explicitly. An unhandled error inside a callback often has nowhere to go.

A worked example: sequential callbacks versus parallel work

Sample data: a page needs a user (120 ms), their orders (200 ms) and their recommendations (150 ms). None needs the others' result.

StyleHow it runsTotal time
Nested callbacks, one after anotheruser, then orders, then recommendations120 + 200 + 150 = 470 ms
All three started togetherwait for the slowestmax(120, 200, 150) = 200 ms

Check: 120 + 200 + 150 = 470, and the slowest of the three is 200. Nesting made the page 270 ms slower for no reason, because the requests did not depend on each other.

Nesting also causes the "pyramid of doom": each step goes one level deeper, and error handling is repeated at every level. MDN's guide on promises uses this pyramid as the motivation for promises, which flatten the chain and give you a single place to catch errors (MDN: Using promises). The decision rule: if steps depend on each other, chain them; if not, start them together.

Callbacks, promises and async/await

ApproachStrengthWeakness
CallbackSimple, works everywhere, no extra conceptsNesting; scattered error handling
PromiseFlat chains, one catchA new object to learn; easy to forget to return
async / awaitReads like normal codeStill promises underneath; sequential by default

Promises do not remove callbacks; .then() itself takes one. They change who owns the control flow. You will still meet callbacks in event handlers, older libraries and SDK options.

Common mistakes

  • Expecting the callback to have run. Code after an asynchronous call runs first. If you need the result, use it inside the callback.
  • Calling the function instead of passing it. setTimeout(go(), 100) runs go now and passes its return value; you wanted setTimeout(go, 100).
  • Losing errors. A failure thrown inside an asynchronous callback does not reach the code that started it.
  • Doing work you cannot wait for on page exit. A callback after a network request may never run if the page closes first. See JavaScript error for how uncaught errors surface.
  • Treating "callback" and "webhook" as the same. A webhook is a callback across a network: you give a URL instead of a function.

Callbacks in tracking code and TapCub

Callbacks appear in tracking in a few concrete places. Using TapCub's documented behaviour:

  1. SPA page views. If your router does not change the address, call window.tapcub.pageview() from the router's route-ready callback, so the view is sent after the page's data is ready. If automatic recording is on and the URL already changed, do not call it again, or you will get a second row once the 2-second window has passed.
  2. Server and mobile SDK errors. The server SDKs take an onError option (named on_error in Python), called for batches that are dropped or rejected; the Android SDK also exposes onConsentChange, onSessionStart, onError and init(callback), which run on the main thread. A code such as send_failed in that callback means the SDK gave up on a batch; see the SDK network notes in the docs.
  3. Do not wait on tracking. The website script prefers sendBeacon, then fetch with keepalive, and has no local queue, so a hit that did not leave before the page closed is gone. Do not make navigation depend on a tracking callback.
  4. See the result in the data. After wiring a route-ready callback, check Web analytics › Realtime or Web analytics › Pages to confirm one view per route change.

TapCub does not run your callbacks or fix asynchronous code; it records what your code reports. Planned event names, such as the ones in All-platform analytics › Data › Tracking plan, show you whether the callback fired as expected through the live verification count.

Sources

Was this explanation clear?

We use your answers to fix and expand this page.

Su He

Data Analyst

Explores traffic sources, conversion funnels, and retention, using clear metric definitions and concrete examples to explain what the numbers mean.

FAQ

Questions people ask

Short answers to the follow-up questions that come up most.

Still have a question?

Chat with the team behind TapCub — we usually reply within a few hours on business days.

What is a callback in simple terms?

It is a function you hand to someone else's code with the instruction "call this when you are done". You decide what happens; the other code decides when.

What is the difference between a callback and a function?

Any function can be used as a callback. The word describes how it is used: it is passed as an argument and called by other code later, instead of being called directly by you.

What is callback hell?

Deeply nested callbacks, each started inside the previous one, with error handling repeated at every level. Promises and async/await flatten the chain and give one place to catch errors.

Is a callback the same as a webhook?

Similar idea, different place. A callback is a function called inside one program. A webhook is a callback across a network: you give a URL, and the other system sends an HTTP request to it when an event happens.

See this number on your own site

Add one script tag for web and apps, and the first reports fill in within minutes.

See your data clearly. Find your growth.

Every click, backed by data. Install one line of code and see your first numbers in a minute.

No credit card · Free plans for analytics and chat · Cookieless analytics