Callbacks
Pass a function to be called later.
Syntax
setTimeout(() => { ... }, 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
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.
function showTooltip() {
console.log("Tooltip visible");
}
setTimeout(showTooltip, 500); // fires after 500msCustom success and error callbacks
Implements a Node-style callback pattern where success and error are separate function arguments.
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.
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