This post intends to figure out how to use Javascript callbacks by understanding how they are used in various Javascript libraries.
Let’s start with the simple setTimeout function. If we consider the code below
const startTimer = (printAction) => {
setTimeout(printAction, 3);
};
const printAction = () => {
console.log('print Action');
}
startTimer(printAction);
We are passing another function (printAction) into setTimeout. setTimeout will then call this function once the timer has finished. The printAction function that is called is a callback.
Since the term callback is used, let’s consider this an analogy to a phone call. We make a phone call to setTimeout and inform it of the callback details, i.e. printAction. setTimeout hangs up the phone, waits till the timer is done and then calls us back with printAction.
Let’s consider another use of callbacks in the example below with the readFile function in the node.js file system to realise a significant advantage of callbacks.
import { readFile } from 'node:fs';
readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
The readFile function takes in the file it needs to read and a callback. The callback is an arrow function with err and data as params. Once readFile is done, it calls the arrow function (callback). We then throw an error if err is present or log the data.
The advantage is that the file is read asynchronously, which is essential in the Javascript world. The main program can continue to execute and respond to other events, whilst the readFile will execute asynchronously and inform us about the results via a callback.
Feel free to suggest anything in the comments section to improve someone’s understanding of callbacks.
Top comments (2)
Hi.
I would suggest adding
js
after the opening backticks to have syntax highlight.Also, since this post is aimed at beginners I would remove the need for
startTimer
as it adds a complexity that's not, IMHO, relevant to the topic.I'd also add a longer timeout value to better see the effect of
setTimeout
.3
is in milliseconds so it will feel like an immediate call toprintAction
.Another possible example of using callbacks:
Thank you for this, was very helpful advice.
I also liked your example of callback. The comments made everything clear!