JavaScript is an event-driven language for one very crucial reason. This indicates that JavaScript will continue to run while listening for additional events instead of waiting for a response before proceeding. Let us take a fundamental example:
function first(){
console.log(1);
}function second(){
console.log(2);
}first();
second();
But what if the first function includes some kind of code that cannot instantly be executed? An API request, for instance, where we must send the request and wait for the answer? The setTimeout, a JavaScript function that calls a function after some time, was used to replicate this behavior. To imitate API requests, we will postpone our work for 500 milliseconds. This will be our new code:
function first(){
setTimeout( function(){
console.log(1);
}, 500 );
}function second(){
console.log(2);
}first();
second();
It doesn’t matter how setTimeout() works at this moment. It is all-important that you realize that our console has shifted. Log(1); within our lag of 500 milliseconds. So now what happens when our functions are invoked?
first();
second();
Even though we originally used the first() function, following the _second() _function, we logged out the result.
Simply put: A callback is a function to be carried out after another feature has been run and the name ‘call back’ is therefore executed.
More complexly put: Functions are objects in JavaScript. This allows functions to be used as an argument and other functions to be returned. These are termed higher-order functions. Functions. A callback function is any function that is supplied as the argument.
It is not that JavaScript did not run our functions as we desired, but that JavaScript did not wait for _first() _response to perform the _second() _before we moved. So why do you display that? Because you can’t just call one function in the appropriate sequence and hope to run it. Callbacks are a means to ensure that specific code is not running until a different execution code is already complete.
#javascript #programming #web-development #software-development #coding