Skip to content

Commit 6bc474a

Browse files
committed
partial fix: what-are-callback-functions-and-how-are-they-used
1 parent b961378 commit 6bc474a

File tree

1 file changed

+9
-7
lines changed
  • questions/what-are-callback-functions-and-how-are-they-used

1 file changed

+9
-7
lines changed

questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@ title: What are callback functions and how are they used?
66

77
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. They are commonly used for asynchronous operations like handling events, making API calls, or reading files. For example:
88

9-
```js
9+
```js live
1010
function fetchData(callback) {
11-
setTimeout(() => {
12-
const data = { name: 'John Doe' };
13-
callback(data);
14-
}, 1000);
11+
// assume an asynchronous operation to fetch data
12+
const data = { name: 'John Doe' };
13+
callback(data);
1514
}
1615

1716
function handleData(data) {
@@ -33,7 +32,7 @@ A callback function is a function that is passed as an argument to another funct
3332

3433
Synchronous callbacks are executed immediately within the function they are passed to. They are often used for tasks that need to be completed before moving on to the next line of code.
3534

36-
```js
35+
```js live
3736
function greet(name, callback) {
3837
console.log('Hello ' + name);
3938
callback();
@@ -44,6 +43,9 @@ function sayGoodbye() {
4443
}
4544

4645
greet('Alice', sayGoodbye);
46+
// Output:
47+
// Hello Alice
48+
// Goodbye!
4749
```
4850

4951
### Asynchronous callbacks
@@ -105,7 +107,7 @@ function sayHello() {
105107
console.log('Hello, world!');
106108
}
107109

108-
setTimeout(sayHello, 2000);
110+
setTimeout(sayHello, 2000); // After 2 seconds elapse, sayHello callback is called
109111
```
110112

111113
## Further reading

0 commit comments

Comments
 (0)