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.
| Kind | When it runs | Examples in JavaScript |
|---|---|---|
| Synchronous | Before the calling function returns | Array.prototype.map(), forEach(), sort() comparator |
| Asynchronous | After the current code finishes, when an event or timer fires | setTimeout(), 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
- Error-first order. Many APIs call
callback(error, result): checkerrorfirst, and only useresultwhen there is none. It makes failure impossible to forget. - Call it once. A callback that can fire twice (once on success, once on a later failure) causes duplicate work.
- Always sync or always async. A function that sometimes calls back immediately and sometimes later is hard to reason about; pick one.
- Keep your own context. The callback may run with a different
thisor after variables changed; capture what you need. - 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.
| Style | How it runs | Total time |
|---|---|---|
| Nested callbacks, one after another | user, then orders, then recommendations | 120 + 200 + 150 = 470 ms |
| All three started together | wait for the slowest | max(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
| Approach | Strength | Weakness |
|---|---|---|
| Callback | Simple, works everywhere, no extra concepts | Nesting; scattered error handling |
| Promise | Flat chains, one catch | A new object to learn; easy to forget to return |
async / await | Reads like normal code | Still 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)runsgonow and passes its return value; you wantedsetTimeout(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:
- 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. - Server and mobile SDK errors. The server SDKs take an
onErroroption (namedon_errorin Python), called for batches that are dropped or rejected; the Android SDK also exposesonConsentChange,onSessionStart,onErrorandinit(callback), which run on the main thread. A code such assend_failedin that callback means the SDK gave up on a batch; see the SDK network notes in the docs. - Do not wait on tracking. The website script prefers
sendBeacon, thenfetchwithkeepalive, 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. - 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
- MDN Web Docs, Callback function.
- MDN Web Docs, Using promises.
Was this explanation clear?
We use your answers to fix and expand this page.
Couldn’t send. Please try again in a minute.
Thanks for the feedback. We’ll use it to improve this page.You’ve already sent feedback on this page. Thanks.

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