12 views

Callback Function in JavaScript

Callback function means that it is a function that executes after another function is executed. And that’s why it’s called callback function.

#synchronous function

    function synch(func){
      func("synchronous")
    }
    synch(alert)
    alert('Test')

#Asynchronous function

setTimeout(alert,1000, "Asynchronous");
    alert('Test')

#Infinity Loop

function _1(){
      console.log('First function')
      _2();
    }
    function _2(){
      console.log('Second function');
      _1();
    }
    _1();

Now what’s the callback job? We know about the asynchronous behavior of JavaScript. If JavaScript takes time to do a task, do not wait and move on to the next code:

    const getCustomFunction = () => {
      setTimeout(function(){
        console.log('A function that takes some time');
      }, 3000)
    }
    const printAnotherFunction = () => {
      console.log('Another Function');
    }
    getCustomFunction();
    printAnotherFunction();

Running this code will show the next as before, and the next one for JavaScript asynchronous behavior:

From the definition of a callback function, we know that it is executed after another function is executed. And so we can use this technique here by writing two functions individually, but we can do it by the callback at the exact time the function is called:

    const getCustomFunction = (callback) => {
      setTimeout(function(){
        console.log('A function that takes some time');
        callback();
      }, 3000)
    }
    const printAnotherFunction = () => {
      console.log('Another Function');
    }
    getCustomFunction(printAnotherFunction);

We passed our function here as an argument inside our Main function call. And then I called it exactly where I needed it. This printAnotherFunction() function here is the callback function. It will give us results like mind. Means one after another. It will wait exactly 3 seconds then give the result. But serial maintenance does. Promise first, the data will come from it, then run the callback function:

1 thought on “Callback Function in JavaScript

Leave a Reply