Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are callback methods?

I'm a programming noob and didn't quite understand the concept behind callback methods. Tried reading about it in wiki and it went over my head. Can somebody please explain this in simple terms?

like image 594
noob_00 Avatar asked Dec 01 '10 11:12

noob_00


People also ask

What are callback methods in Java?

A callback method in java is a method that gets called when an event (call it E ) occurs. Usually you can implement that by passing an implementation of a certain interface to the system that is responsible for triggering the event E (see example 1).

What are the types of callback?

There are two types of callbacks, differing in how they control data flow at runtime: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known as asynchronous callbacks).

What is an example of callback?

We want to log a message to the console but it should be there after 3 seconds. In other words, the message function is being called after something happened (after 3 seconds passed for this example), but not before. So the message function is an example of a callback function.


1 Answers

The callback is something that you pass to a function, which tells it what it should call at some point in its operation. The code in the function decides when to call the function (and what arguments to pass). Typically, the way you do this is to pass the function itself as the 'callback', in languages where functions are objects. In other languages, you might have to pass some kind of special thing called a "function pointer" (or similar); or you might have to pass the name of the function (which then gets looked up at runtime).

A trivial example, in Python:

void call_something_three_times(what_to_call, what_to_pass_it):     for i in xrange(3): what_to_call(what_to_pass_it)  # Write "Hi mom" three times, using a callback. call_something_three_times(sys.stdout.write, "Hi mom\n") 

This example let us separate the task of repeating a function call, from the task of actually calling the function. That's not very useful, but it demonstrates the concept.

In the real world, callbacks are used a lot for things like threading libraries, where you call some thread-creation function with a callback that describes the work that the thread will do. The thread-creation function does the necessary work to set up a thread, and then arranges for the callback function to be called by the new thread.

like image 144
Karl Knechtel Avatar answered Sep 24 '22 18:09

Karl Knechtel