DEV Community

adarsh04
adarsh04

Posted on

Javascript callbacks

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);
Enter fullscreen mode Exit fullscreen mode

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);
});

Enter fullscreen mode Exit fullscreen mode

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.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/API/setTimeout 2.https://nodejs.org/api/fs.html#fsreadfilepath-options-callback

Top comments (2)

Collapse
 
joolsmcfly profile image
Julien Dephix • Edited

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 to printAction.

const printAction = () => {
  console.log('print Action');
}

setTimeout(printAction, 3000); // will call printAction after 3 seconds
Enter fullscreen mode Exit fullscreen mode

Another possible example of using callbacks:

const longRunningFunction = async (callback) => {
    // some code that takes a long time to run: call to a server or something client-side

    // long running code is over, let's call... the callback
    typeof callback === "function" && callback();
}

const notifyUser = () => {
    // some sort of notification: alert, modal, your choice!
    console.log("Notification sent!");
}

longRunningFunction(notifyUser);
console.log("I am not waiting for longRunningFunction to finish!")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adarsh04 profile image
adarsh04

Thank you for this, was very helpful advice.
I also liked your example of callback. The comments made everything clear!