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