What are callback functions and how are they used?
TL;DR
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:
What are callback functions and how are they used?
Definition
A callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. This allows other code to run in the meantime and prevents blocking.
Synchronous callbacks
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.
Asynchronous callbacks
Asynchronous callbacks are used for operations that take some time to complete, such as reading files, making HTTP requests, or handling events. These callbacks are executed after the asynchronous operation has finished.
Common use cases
Event handling
Callbacks are often used in event handling. For example, in JavaScript, you can pass a callback function to an event listener.
API calls
Callbacks are frequently used in making API calls to handle the response data.
Timers
Callbacks are also used with timers like setTimeout
and setInterval
.