Callbacks

Pass a function to be called later.

SyntaxsetTimeout(() => { ... }, 1000)

A callback is a function passed to another function to be run later. Callbacks are the foundation of asynchronous code, where work finishes at some point in the future.

setTimeout

setTimeout(fn, ms) runs a callback after a delay in milliseconds.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Pass a function to setTimeout to delay a tooltip display by 300ms after the user hovers.
  • Provide a custom comparator callback to Array.sort to sort products by price.
  • Supply an error-handling callback to a file-reading function that fires only on failure.

More examples

setTimeout with a callback

Passes showTooltip as a callback to setTimeout; JavaScript calls it after the specified delay.

Example · js
function showTooltip() {
  console.log("Tooltip visible");
}
setTimeout(showTooltip, 500); // fires after 500ms

Custom success and error callbacks

Implements a Node-style callback pattern where success and error are separate function arguments.

Example · js
function loadUser(id, onSuccess, onError) {
  const users = { 1: "Alice", 2: "Bob" };
  const user = users[id];
  if (user) onSuccess(user);
  else onError("User not found");
}
loadUser(1, name => console.log("Got:", name), err => console.error(err));

Array method with callback

Passes arrow function callbacks to filter and sort to control element selection and ordering.

Example · js
const nums = [3, 1, 4, 1, 5, 9];
const evens = nums.filter(n => n % 2 === 0);
nums.sort((a, b) => b - a);
console.log(evens); // [4]
console.log(nums);  // [9, 5, 4, 3, 1, 1]

Discussion

  • Be the first to comment on this lesson.
Callbacks — JavaScript | SoundsCode