Could someone explain, why do we use callback in JavaScript? I found examples, but they could be implemented by using the normal functions. What is the advantage of using it? I got answers to "how" to use it and not "why and when" do we need to use it.
Typically, I found it being used in AJAX. on the httpRequest.onreadystatechange
. Is this similar to Java's multi-threading? How and where is the listener for the response? Is asyncronous programming akin to multi-threading?
In the following code, how is the flow of control:
function some_function(arg1, arg2, callback) { var my_number = Math.ceil(Math.random() * (arg1 - arg2) + arg2); callback(my_number); some_different_function_not_callback(arg1); } some_function(5, 15, function(num) { console.log("callback called! " + num); });
From the JQuery website:
The special thing about a callback is that functions that appear after the "parent" can execute before the callback executes" (ref: http://docs.jquery.com/Tutorials:How_jQuery_Works)
Could someone explain me this line with an example?
Callback functions have access to both their own scope plus the scope of the code that calls them plus the global scope of the calling code. So callback functions are handier to manage codewise, especially in larger JS applications where data is passed across several module boundaries during execution of a task.
A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. In other words also, we may say that, promises are the ideal choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation.
The main browser process is a single threaded event loop. If you execute a long-running operation within a single-threaded event loop, the process "blocks". This is bad because the process stops processing other events while waiting for your operation to complete. 'alert' is one of the few blocking browser methods: if you call alert('test'), you can no longer click links, perform ajax queries, or interact with the browser UI.
In order to prevent blocking on long-running operations, the XMLHttpRequest provides an asynchronous interface. You pass it a callback to run after the operation is complete, and while it is processing it cedes control back to the main event loop instead of blocking.
There's no reason to use a callback unless you want to bind something to an event handler, or your operation is potentially blocking and therefore requires an asynchronous programming interface.
This is an excellent video discussing more about the event loop used in the browser, as well as on the server side in node.js.
EDIT: that convoluted line from the jQuery documentation just means that the callback executes asynchronously as control is ceded back to the main event loop.
parent_function(function () { console.log('Callback'); }); parent_doesnt_block(); // <-- function appears after "parent" therefore_execution_continues(); // Maybe we get 'Callback' in the console here? or maybe later... execution_still_continues();
Not quite like multithreading...
You use a callback anytime you need to wait on something external to your primary JS code. In a browser this is used a ton for AJAX, and in node.js it's used for every single thing that calls out to the system (file access, networks access, database requests, etc).
Let's say you want to fire an ajax request everytime a user clicks a button. Now lets say that ajax request takes 10 seconds to complete. The user then clicks 10 of these buttons before those 10 seconds are up. This would repeatedly call a function like this:
var clicked = function() { doAjax('/some/path.json', function(result) { updatePageWith(result.widgets); }); };
This runs code in the JS engine for only long enough to make the request. Then it idles while it waits. Other JS can run at this point, the UI is totally fluid and interactive, everything is awesome. Then suddenly, all 10 of those requests resolve at once. And then our callback is invoked 10 times like magic.
This works because every time we call clicked()
we are creating a new function object, and passing it to the doAjax()
function. So there are 10 unique callback function objects hanging out in memory, each one bound to a specific request by the doAjax()
function. When a request returns, it finds the associated callback object and calls it.
The huge advantage here is that, although javascript is single threaded, you never tie up that thread with waiting. If you JS thread is busy, it should only ever be because it's actively running code. So even though JS is single threaded, it's trivial for your code to implicitly hold the state of any number of any kind of asynchronous tasks.
The synchronous method of callbacks are used for a different purpose usually. Like listeners or delegates. Like telling object A to callback when it's data changes. While not strictly asynchronous, you usually aren't calling that callback immediately. Instead it will be called later in response to some sort of user action of event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With