Why do we need “callback functions”?

I am reading the book programming in Lua. It said that

Closures provide a valuable tool in many contexts. As we have seen, they are
useful as arguments to higher-order functions such as sort. Closures are valuable for functions that build other functions too, like our newCounter example;
this mechanism allows Lua programs to incorporate sophisticated programming
techniques from the functional world. Closures are useful for callback functions,
too. A typical example here occurs when you create buttons in a conventional
GUI toolkit. Each button has a callback function to be called when the user
presses the button; you want different buttons to do slightly different things
when pressed. For instance, a digital calculator needs ten similar buttons, one
for each digit. Y ou can create each of them with a function like this:

function digitButton (digit)
  return Button{label = tostring(digit),
                action = function ()
                  add_to_display(digit)
                  end}
end

It seems that if I call the digitButton, it will return the action (this will create a closure), so, I can access the digit passed to digitButton.

My question is that:

Why we need call back functions? what situations can I apply this to?


The author said:

In this example, we assume that Button is a toolkit function that creates new
buttons; label is the button label; and action is the callback closure to be
called when the button is pressed. The callback can be called a long time after
digitButton did its task and after the local variable digit went out of scope, but
it can still access this variable.

according to the author, I think a similar example is like this:

function Button(t)
  -- maybe you should set the button here
  return t.action -- so that you can call this later
end

function add_to_display(digit)
  print ("Display the button label: " .. tostring(digit))
end

function digitButton(digit)
  return Button{label = tostring(digit),
                action = function ()
                           add_to_display(digit)
                           end}
end

click_action = digitButton(10)
click_action()

thus, the callback can be called a long time after digitButton did its task and after the local variable digit went out of scope.

1

Guy 1 to Guy 2: hey dude I wanna do something when a user clicks in there, call me back when that happens alright?

Guy 2 calls back Guy 1 when a user clicks here.

4

No, it will never return the action. The button will execute it when the user clicks on it. And that is the answer. You need callback functions when you want to define actions that should happen in another component in reaction to an event you don’t control (the event loop, which is part of the system, will execute a method of the button which will in turn execute the action).

4

I think a better example for the use of callbacks is in asynchronous functions. I can’t speak for Lua, but in JavaScript, one of the most common asynchronous action is contacting a server via AJAX.

The AJAX call is asynchronous, meaning if you do something like this:

var ajax = ajaxCall();
if(ajax == true) {
  // Do something
}

the contents of the if block will not reliably run correctly, and when it does, it’s only because the ajaxCall() function happened to finish before the execution reached the if statement.

However, callbacks eliminate this issue, by ensuring the asynchronous call is finished before calling the required function. So, your code would change to something like this:

function ajaxCallback(response) {   
  if(response == true) {
    // Do something   
  }
}

ajaxCall(ajaxCallback);

The purpose of this is to allow you to do things like gather data, without interfering with other things, such as drawing the interface. If the data gathering was synchronous, then the interface would become unresponsive as the application waited to get the data. An unresponsive interface is very bad for user experience, because most users will think the application has “crashed” and will try to terminate the process.

To see this in action, you just need to look at any website that does any kind of updating without reloading the whole page. Twitter, LinkedIn, and the StackExchange sites are good examples. Twitter’s “endless scrolling” of feeds, and SE’s notifications (for both user notifications, and notifications that a question has new activity), are powered by asynchronous calls. When you see a spinner somewhere, that means that section has made an asynchronous call, and is waiting for that call to finish, but you can interact with other things on the interface (and even make other asynchronous calls). Once that call finishes, it will react and update the interface accordingly.

You asked the question

Why we need “call back functions”?

I will try to answer it in a concise and clear manner (if I fail at that, please refer to the wiki link at the bottom of this answer).

Callbacks are used to defer the specific implementation of something to the last possible moment.

The button example is a good illustration of this. Say you want to have a button in your application that prints a page to the printer, we could imagine a world where you would have to code an entire new PrinterButton class in order to do this.

Luckily, we have the notion of callbacks (inheritence and the use of the template pattern is also a kind of callback semantic) so we do not need to do that.

Instead of re-implementing every aspect of a button, what we do is to add to the implementation of the button. The Button has the concept of doing something when it’s pressed. We simply tell it what that something is.

That mechanism of injecting behavior into frameworks is called callbacks.

Example:

Let’s inject some behavior into an HTML button:

<button onclick="print()">Print page through a callback to the print() method</button>

In this instance, onclick points to a callback, which for this example is the print() method.


http://en.wikipedia.org/wiki/Callback_(computer_programming)

2

Why we need call back functions? what situations can I apply this to?

Callback functions are very useful in event-driven programming. They allow you to set up your program in such a way that events will trigger the correct code. This is very common in programs with GUIs where users can click on any element on the UI (such as buttons or menu items) and the appropriate code will be run.

2

What happens without callbacks:

Guy 1: Okay, I’m waiting for that thing to happen. (whistles, twiddles thumbs)

Guy 2: Dammit! Why is Guy 1 not showing me stuff? I want to see stuff happening!! Where’s my stuff? How is anybody supposed to get anything done around here?

Firstoff, the term callback refers to a closure that is being used for something.

For example, suppose you create a closure function and just store it in a variable. It isn’t a callback, because it isn’t being used for anything.

But, suppose you create a closure and store it somewhere that it will get called when something happens. It is now termed a callback.

Usually, callbacks are created by different parts of the program than the parts that call them. So it’s easy to imagine that some parts of the program are “calling back” the other parts.

Simply put, callbacks allow one part of the program to tell another part to do something (anything) when something happens.

As for variables being kept alive due to being used in a closure, that’s a completely different feature called upvalues (a.k.a. “extending the lifetime of local variables” among those who don’t speak Lua). And it’s quite useful as well.

2

Callbacks have been around since the early days of Fortran, at least.
For example, if you have an ODE (ordinary differential equation) solver, such as a Runge-Kutta solver, it might look like this:

subroutine rungekutta(neq, t, tend, y, deriv)
  integer neq             ! number of differential equations
  double precision t      ! initial time
  double precision tend   ! final time
  double precision y(neq) ! state vector
  ! deriv is the callback function to evaluate the state derivative
  ...
  deriv(neq, t, y, yprime) ! call deriv to get the state derivative
  ...
  deriv(neq, t, y, yprime) ! call it several times
  ...
end subroutine

It enables the caller to customize the behavior of the subroutine by passing it a special-purpose function to be called when necessary.
This allows the ODE solver to be used to simulate a wide variety of systems.

Stumbled upon this and wanted to provide a more up to date answer…

Callback functions allow us to do something with data at a later time, allowing the rest of our code to run, instead of waiting for it. The asynchronous code allows us this luxury of executing anything later. The most readable example of callback functions I have come across are Promises in JavaScript. In the example below every time you see function(result) or (newResult) or (finalResult)… these are callback functions. The code within their curly brackets is executed once the data comes back from the server. Only at this point would it make sense to execute these functions since now the data they need is available.

doSomething().then(function(result) {
  return doSomethingElse(result);
})
.then(function(newResult) {
  return doThirdThing(newResult);
})
.then(function(finalResult) {
  console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);

the code is taken from…
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Hopefully, this helps someone. This is what helped ME understand callbacks 🙂

2

I don’t know lua but in general callback methods some what like multithreading.
For example in mobile application development programming most of the applications are functioning like sending request to the server and playing with UI with the data came as response from the server. When the user sends a request to server, it will take time to get response from server but for best UX UI should not stuck.

Because of this we use multiple thread to do parallel operations. When we get the response from the server we need to update UI. we have to notify from that thread to update. from the functional world. This type of function calls are called callback methods. When you call these methods the controle should have return to the main thread. For example callback methods are blocks in objective-C.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật