## WHAT
### What it is?
A **callback function** is a function that you pass into another function as an argument, and it's called (or "called back") after the first function finishes running.
### Why use it?
- mostly use in [[async]]
- 事件处理:例如在浏览器中处理用户点击或其他事件,
- Event listeners: `element.addEventListener('click', callback)`
- 定时任务:例如使用 `setTimeout` 或 `setInterval`。
- Array methods like `.map()`, `.forEach()`, `.filter()`
## Common Use Cases
### 1. Asynchronous operations
When you want to run some code _after_ something finishes (like loading a file or getting API data).
```js
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
```
这里的箭头函数就是 callback,它等 `setTimeout` 结束后再执行。
### 2. Array methods
Functions like `.forEach()`, `.map()`, `.filter()` all take a callback to apply to each item.
```js
const nums = [1, 2, 3];
nums.forEach(num => {
console.log(num * 2);
});
```
### 3. Event listeners
Browser events use callbacks to define what happens when the event fires.
```js
button.addEventListener('click', () => {
console.log("Button was clicked!");
});
```
### 4. Custom function logic
You can pass logic as a callback to make functions more reusable.
```js
function doSomething(data, callback) {
console.log("Processing:", data);
callback();
}
doSomething("Hello", () => {
console.log("Done!");
});
```