Anybody explain me callback function?

Basic concept of callback function how they works and what is the practical fields of callbacks?

Let’s say this topic is execution thread and your question is main function that is asynchronous. Why async? Because you cannot get answer immediately. Now question, how can you know when this function is fulfilled (answer is posted)? You are passing a callback function NotifyMe(), so when I hit “Reply” button you will get notified about it. This is a callback in a nutshell.

1 Like
<script>

    function CustomEventListener(aneventtype,callbackFunction){

        // wait for user action...

        let eventObj = {

            type: "keypress",

            key: 'k',

            duration: 0.0002345,

            code: "capK"

        }

        if(eventObj.type === aneventtype){

            callbackFunction(eventObj);

        }

    }

    function callbackFunction(e){

        console.log(e);

    }

    CustomEventListener("keypress",callbackFunction);

</script>

In this example I will try to recreate dummy addEventListener function and I will do this work simply a normal function call and It work’s in same way.

Like this: :point_down:t3::point_down:t3::point_down:t3:

<script>

        function CustomEventListener(aneventtype){

            // wait for user action...

            let eventObj = {

                type: "keypress",

                key: 'k',

                duration: 0.0002345,

                code: "capK"

            }

            if(eventObj.type === aneventtype){

                callbackFunction(eventObj);

            }

        }

        function callbackFunction(e){

            console.log(e);

        }

        CustomEventListener("keypress");

    </script>

So why I use call back?

You use a callback parameter so when it’s going to be given a different parameter value, It’s going to callback the function that you gave to the parameter instead of the one single function that you run.

Two reasons:

  1. Your custom event listener might listen for many events and not all of which want the same callback. For example I want one thing to happen on click and other thing to happen on resize. If you just phrase it like this it will become quite obvious:
  • On CLICK I WANT THIS;
  • On RESIZE I WANT THAT;

WantThis and WantThat are your callbacks!

  1. Normally event listener and event emitter are very different interfaces that are not connected in any way (That’s the main reason behind creation of event-based communication in the first place). Callback is a property of emitter (usually an app script expecting user to behave in certain way) and Listener is a property of hosting interface (usually one of the browser’s interface). It is incorrect for listener to assume it knows what emitter wants.
1 Like