Whats is Callback Function



Comments



Description

How to explain callbacks in plain english?How are they different from calling function from another function? How to explain callbacks in plain English? How are they different from calling one function from another function taking some context from the calling function? How can their power be explained to a novice programmer? function callback edited Sep 14 at 22:07 David Robinson 14.9k 2 14 37 asked Mar 7 at 5:25 Yahoo-Me 344 3 14 80% accept rate 4 its good question – Balaswamy vaddeman Mar 7 at 5:46 I believe the scientific name for it is continuation-passing style. You can search for this on wiki. – lightblade Mar 11 at 4:48 There's some good answers to an identical question on Quora also – dbr Mar 11 at 4:56 5 1 I wonder how come so many answers have "-1" (I could easily guess though :)) – AoeAoe Mar 11 at 17:25 Relevant question: stackoverflow.com/questions/824234/what-is-a-callback-function – moodywoody Mar 12 at 5:26 show 1 more comment feedback 27 Answers Often an application needs to execute different functions based upon its context/state. For this, we use a variable where we would store the information about the function to be called. According to its need the application will set this variable with the information about function to be called and will call the function using the same variable. In javascript, the example is below. Here we use method argument as a variable where we store information about function. http://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o... function processArray(arr. Therefore. If your spouse was as stupid as a computer. she would sit at the door and wait for the package until it came (NOT DOING ANYTHING ELSE) and then once it came she would bring it over to the neighbors. You are out of town. before we write to it. for (var i = arr. we WAIT for the file to open. Tell your wife that ONCE she receives the package. } var arr = [1. the receiving of the package is the "event" and the bringing it to the neighbors is the "callback". i--) resultArr[i] = callback(arr[i]).") # now we can continue doing the other.. you want it brought over the the neighbors. i >= 0.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. In our example. but computers don't have the same kind of common sense. 2. -2. Your wife "runs" your instructions to bring the package over only when the package arrives. Then. But there's a better way. This "blocks" the flow of execution. she can go about life normally UNTIL she receives the package. Much better! This kind of thinking is obvious in daily life.length-1. A "callback" is any function that is called by another function which takes the first function as a parameter. we can write to it fileObject. var arrReturned = processArray(arr. A lot of the time. 3. she should bring it over the neighbors. . -4] edited Mar 10 at 8:24 answered Mar 10 at 8:17 Niraj Nawanit 662 3 10 feedback I am going to try to keep this dead simple. function(arg) {return arg * -1. a "callback" is a function that is called when something happens. once you get the package. -3. That something can be called an "event" in programmer-speak. Consider how programmers normally write to a file: fileObject = open(file) # now that we have WAITED for the file to open. and our program cannot do any of the other things it might need to do! What if we could do this instead: # we pass writeToFile (A CALLBACK FUNCTION!) to the open function http://stackoverflow.}). return resultArr. You could tell her to get the package and bring it to the neighbors. and so you leave instructions for your spouse. 4]. // arrReturned would be [-1. Imagine this scenario: You are expecting a package in a couple of days. The package is a gift for your neighbor. totally unrelated things our program does Here.write("We are writing to the file. callback) { var resultArr = new Array().. js to get some real practice with this kind of thinking. . a callback function is like a Worker who "calls back" to his Manager when he has completed a Task. For example in PHP array_filter() and array_map() take callbacks to be called in a loop. It's pretty cool! Check out Node. Often you use callbacks when you need to call a function with arguments which would be processed in the process of another function. writeToFile) # execution continues flowing -. With a callback.fileObject = open(file. showNowLoading(false). Some code without a callback: function grabAndFreeze() { showNowLoading(true). do_other_stuff(). // not called until data fully downloaded } http://stackoverflow. but while we wait WE CAN DO OTHER THINGS! It turns out we do this with some languages and frameworks. edited Apr 2 at 17:44 answered Mar 11 at 4:24 Josh Imhoff 617 1 2 7 6 1 Good explanation!!! I am hoping for a wiki kinda answer for this question.. but does not cover all common use cases for callbacks.json'). How can their power be explained to a novice programmer? The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. How are they different from calling one function from another function taking some context from the calling function? It is true that you are calling a function from another function.we don't wait for the file to be opened # ONCE the file is opened we write to it. Downloading the new data may take some time. so you can change which Function to call based on the state of the system (like the Strategy Design Pattern). /* User Interface 'freezes' while getting data */ processData(jsondata). your entire User Interface would "freeze up" while downloading the new data. – Haralan Dobrev Mar 13 at 23:33 feedback How to explain callbacks in plain English? In plain English. Without callbacks. var jsondata = getData('http://yourserver..com/data/messages.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. – Arkid Mitra Mar 11 at 4:36 This is correct. or you would need to refresh the entire page rather than just part of it. but the key is that the callback is treated like an Object. you can insert a "now loading" image and replace it with the new data once it is loaded. count. count.results ? jsondata.results ? jsondata.results. var count = jsondata. showNowLoading(false. dtable). dtable].length : 0.. $('#results'+ uiElem). you can inline the function so it sees the data in the calling context: /* Grab messages. } function grabAndGo() { // and don't freeze showNowLoading(true).join(''). . 'new items']. no frozen User Interface! */ do_other_stuff(). $('#results_messages'). var count = jsondata.json data is downloaded: http://stackoverflow. } With Callback: Here is an example with a callback.text(counterMsg).length : 0. // no new chatters/messages/etc defaultResultsMsg = ['(no new '. $('#results_messages').join(' ')). 'new items']. $('#results_messages'). /* Call processDataCB when data is downloaded.html(now_loading_image). $('#counter_messages').join(' ')).getJSON("http://yourserver.text(['Fetched'.*/ function grab(dtable. cb) { if (null == dtable) { dtable = "messages". dtable.results. counterMsg = ['Fetched'. To create the closure .getJSON("http://yourserver. etc by changing dtable.results ? jsondata. } var uiElem = "_" + dtable.html(jsondata. which is like the Worker needing to get information from the Manager before he can complete his Task. 'new'. Run callback cb when done.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. $('#counter_messages'). cb || function (jsondata) { // Using a closure: can "see" dtable argument and uiElem variables above. showNowLoading(true. ')'].text(['Fetched'.results || defaultResultsMsg). // called immediately } Usage: // update results_chatters when chatters. }).results. count.html(now_loading_image). // called immediately } With Closure: Often the callback needs to access state from the calling function using a closure . chat users. $('#counter' + uiElem). $.json". dtable). processDataCB).com/data/messages. using jQuery's getJSON: function processDataCB(jsondata) { // callback: update UI with results showNowLoading(false).function processData(jsondata) { // do something with the data var count = jsondata. $('#results' + uiElem).html(jsondata.length : 0. $. /* User Interface calls cb when data is downloaded */ do_other_stuff().json".results || '(no new messages)').join(' ').com/user/"+dtable+"..results || '(no new messages)').html(jsondata. com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. it sees a blank line.com/jQuery. You do not change the form (the code. Closure Finally.. http://stackoverflow.json data is downloaded grab("messages"). – TarkaDaal Mar 16 at 10:14 feedback In non-programmer terms. but Everyone can write a different emergency contact number. But. you do not use a pencil to fill in a blank on a sheet of paper. When it tries to figure out what to do with the string.. The inner function has access to the vars and parameters of the outer function. (just because Yahoo-Me asked for it) – f13o Mar 13 at 21:09 +1. The first paragraph is bang on the money.jquery. as a callback function). you use the function set_print_callback(the_callback) .there is code inside.com/josher19/jQuery-Parse answered Mar 12 at 4:12 user508994 283 1 5 +1 Nice and clear. take some C code that performs a function. here is a definition of closure from Douglas Crockford: Functions can be defined inside of other functions. There is a blank line there. Example 1: Callbacks are used as customized methods.json" data is loaded: grab("history". Everyone gets the same blank form. You write in someone's name and phone number. // update results_messages when messages. possibly for adding to/changing a program's behavior. usually someone else's).com/survey. the rest of it goes into computer science jargon quite quickly... However you can fill in missing pieces of information (your number).crockford. If an emergency occurs. then that person gets called. // call myCallback(jsondata) when "history. However. the outer function's vars also survive. – Christoph Mar 13 at 18:38 although not "plain english" -. . but does not know how to print output. a callback is a fill-in-the-blank in a program.grab("chatters").com/jQuery. All it can do is make a string.html http://api. See also: http://javascript.jquery. This is key.getJSON/ http://github. myCallback).when/ http://api. For example. the programmer gave you the blank to write your callback in! In this example. A common item on many paper forms is "Person to call in case of emergency". If a reference to an inner function survives (for example. It doesn't make much sense. but that is a part of their power) answered Mar 12 at 17:13 Syphyreal 113 3 I think this is the clearest explanation here. You've now filled in this blank line in the program.g.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. and the_callback is your information you are filling in. If that line is blank nothing will be done. but it's permissible. When a button is clicked. You could put "555-555-1212" in the emergency number blank. You could call the method run_computations or butter_the_biscuits as long as you put that callback's name in the proper blank. A can do further processing inside the callback function. and follow the instructions there (i. set_print_callback is the pencil. Gui programming works much the same way.e. to a log file. you go and read what is written on the paper form. It goes and looks for the callback. However.. This callback happens to be in a blank labeled "Here's what you do when Button1 is clicked" Most IDEs will automatically fill in the blank for you (write the basic method) when you ask it to (e. Final note: That blank line that you're filling in with the callback? It can be erased and re-written at will.The blank variable in the module/code is the blank line. So all B has to do now. or any combination thereof. call the function you put there.. it will look at that blank line. answered Mar 7 at 5:44 Gargi Srinivas 441 1 4 http://stackoverflow. All it knows is an address to a particular function (of module A) through a function pointer that is provided to it by module A. *) A clear advantage here is that you are abstracting out everything about module A from module B. and then call the number you read. – pablaasmo Mar 14 at 7:35 feedback Always better to start with an example :). this allows the possibility of printing to screen. over a network connection. is "callback" into module A when a particular event/condition occurs by using the function pointer. Example 2: When you get told you need to call an emergency number.) Practically. the program needs to figure out what to do next. However that blank can have any method you darn well please. You want module A to be notified when some event/condition occurs in module B. . Let's assume you have two modules A and B. Whenever it needs to print output. to a printer. You have filled in the blank with what you want to do. Module B does not have to care who/what module A is. button1_clicked ). (whether you should or not is another question. module B has no idea about your module A. one is how a callback works (passing around a function that can be called without any knowledge of its context). since this usually takes time.) Because you provided a "callback function" that can be "called" at any time. johny puts a note together with the request form asking them to call him when the stapler is ready for pickup. when you call it you are then waiting for it to be finished http://stackoverflow. so meantime he can go do something else like napping on his desk. Ordinarily. but without further measures. the other what it's used for (handling events asynchronously). Normally. Now the callback would be the bell at your front door. The analogy of waiting for a parcel to arrive that has been used by other answers is a good one to explain both. To humans. this sounds silly. You provide the parcel service with a way to notify you of the parcel's arrival without them having to know where (even if) you are in the house.214 8 45 139 feedback You have some code you want to run.feedback Johny the programmer needs a stapler. . this is totally natural to a computer. some "bells" actually dispatch a phone call. He examines you and determines you need some medication. you would tell the computer to expect a parcel. after filling the request form he can either stand there and wait for the clerk go look around the warehouse for the stapler (like a blocking function call) or go do something else meantime. possibly indefinitely if it never arrives. answered Mar 11 at 14:56 tovmeod 362 1 9 feedback You feel ill so you go to the doctor. answered Mar 11 at 3:33 effigy 51 1 feedback There's two points to explain. Later your pharmacy calls to tell you your prescription is ready. so he goes down to the office supply department and ask for one. You go and pick it up. or how the bell works. He prescribes some meds and calls the prescription into your local pharmacy.. you can now stop sitting at the front porch and "handle the event" (of parcel arrival) whenever it's time.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. it would now sit there and wait (and do nothing else) until the parcel arrives. (For instance. You go home. out of context. answered Mar 11 at 9:05 Hanno Fietz 6. In a computer program.. and each new client (the called-back "function") changes the result of your work deciding what he wants about the picture (the decision made by the clients are the returned result from the "callback function"). And at some later point->Deal with results of Processing. An alternative method is to run this code in parallel and carry on with your own work. the picture is the parameter. a program to call an another program providing some previously defined parameters and can expects some results (this is the contract or operation signature). call me on my cell and read it back to me. lets suppose you are a painter (here you are the main program. functions..com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. edited Mar 15 at 13:41 answered Mar 13 at 22:44 Luciano 371 1 9 feedback Let's pretend you were to give me a potentially long-running task: get the names of the first five unique people you come across. and others). objects and all others unities of code ran by computers. With callback you can instructs by parameters.. "When you've got the list. Normal code: Ask for Information->Process Information->Deal with results of Processing->Continue to do other things. In the above example you are a painter and "delegate" to others the job to approve the result.before you carry on (which can cause your app to go grey/produce a spinning time for a cursor). in that case you can pass in the name/location of the code you want it to call when it's done. and even with a kind of "dynamic behavior" determined by certain conditions. he decides if the picture is good (your client is the third-party program). This is a "call back". You're not really interested in sitting on your hands while I'm running around so you say. So. Here's the number. With callbacks: Ask for Information->Process Information->Continue to do other things. The human world used as example to callback is nice explained when you are doing some job. that paints) and call your client sometimes to ask him to approve the result of your job. a program is exactly a sequence of instructions which are executed sequentially one after the other. This technique is the foundation of polymorphism applied to programs. http://stackoverflow.". . so these results can be produced/processed by third-party program which wasn't previously known. all possible scenarios shall be previously programmed. But what if your original code needs to do different things depending on the response from the code it called? Well. If we need to provide a real dynamic behavior to a program we can use callback. answered Mar 11 at 11:24 Andrew Ducker 574 3 6 20 feedback Without callback neither others special programming resources (like threading. I hope this explanation can be useful. This might take days if I'm in a sparsely populated area. so. Joe does not need to know how the door bell works or where it is. edited Mar 16 at 21:39 answered Mar 13 at 23:36 steamer25 2. i++) { lottoNumbers. Check the window every 5 minutes to see if Joe is out 2.g. She gives him a "function" to ring the door bell. Jane. } }. Joe is driving today. var callback = function(theNames) { for (var i=0. http://stackoverflow. In Ajax for example events can be "success" or "failure" of the asynchronous request and each can have the same or different callbacks.. ring the door bell when he's there. This is where setting up the callback with Joe requires parodying the method so that "this" refers to the right object.length. David and Samantha share a carpool to work. callback).864 7 16 feedback In plain english a callback is a promise. Joe. In this example the "event" is Joe's arrival.executeQuery("SELECT name " + "FROM tblEveryOneInTheWholeWorld " + "ORDER BY proximity DESC " + "LIMIT 5".length). i<theNames. We also need to understand "closures" and application context. What "this" refers to can easily confuse JavaScript developers.e. In this example within each person's "ring_the_door_bell()" method/callback there might be some other methods that each person need to do based on their morning routine ex. In JavaScript it might look something like this: var lottoNumbers = []. . Jane tells Joe to ring her doorbell when he's outside. "turn_off_the_tv()".You've given me a callback reference--a function that I'm supposed to execute in order to hand off further processing.length < 5) { playGolf(). while (lottoNumbers.. Option 1: This is more like a polling example where Jane would be stuck in a "loop" checking if Joe is outside. Jane can't do anything else in the mean time. Keep doing their thing until Joe rings the door bell. db. In terms of JavaScript applications and callbacks. Jane. Option 2: This is the callback example. David and Samantha have a couple of options: 1.push(theNames[i].. E.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. We would want "this" to refer to the "Jane" object or the "David" object so that each can setup whatever else they need done before Joe picks them up. This could probably be improved in lots of ways. he just needs to call that function i. call the red phone and tell the person that answers that you've timed out. you could provide a second callback: if it ends up taking longer than an hour. Callbacks are driven by "events". } playLotto(lottoNumbers). With callbacks.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o." depending on the programming language. For example." This mechanism has a great many possible uses." "closure. It might even choose the callback from a set of possible callbacks.. a sorting function might take a callback as a parameter. might be the address of the callback. answered Mar 13 at 20:15 David Casseres 34 4 feedback A callback is a method that is scheduled to be executed when a condition is met. the browser will look at the list of callbacks for that event and call your method. or some other sort of pointer. or if it will be executed at all. A callback is a way to handle events asynchronously. You can never know when the callback will be executed. the word "function" in the above discussion might be replaced by "block.Hope that helps! answered Mar 12 at 3:44 Nael El Shawwa 300 1 8 feedback A callback is a function that will be called by a second function. you register your email on a list to be notified when the game is available. depending on the programming language. The principal is the same. supplying parameters depending on the circumstances at that moment. edited Mar 11 at 17:21 answered Mar 11 at 17:09 Optimist 269 1 5 http://stackoverflow. This "identity. or passed to the second function as a parameter. or it might be the name of the function. Instead of going to the store every day to see if it is in. and this callback might be a function for comparing two elements to decide which one comes first. When the time comes." etc. By the way. . You register a callback method for a button and continue doing other tasks. When/if the user cicks on the button. the designer of a function can let it be customized by having it call whatever callbacks are provided. You are waiting for Half-Life 3. The advantage is that it frees your program and CPU cycles to perform other tasks while waiting for the reply. The email becomes your "callback" and the condition to be met is the game's availability." "lambda. knowing its "identity. The programming language must provide some kind of syntax to allow the second function to call the callback. we store or pass some information that unambiguously identifies the function.. So the identity of the callback function is stored somewhere. A "programmers" example is a web page where you want to perform an action when a button is clicked. the second function can call the callback. An "real world" example is a local video game store. This second function doesn't know in advance what function it will call. stackexchange. you cannot make a data structure with functions(like an array or a linked list of functions). The second use of callbacks coming in my mind is higher order functions.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. or any other things. The most common use of callbacks is seen in event driver programming. For square roots. Then it performs the callback on each of the item of the array and return the results in another array. Assuming you are using C/C++. we get a doubled valued array.SE programmers. First show your students how to use and manipulate variables using pointers alongside using the normal variable identifiers. just send appropriate callback. This cannot be done with normal functions. Where one or more functions are executed based on some incoming signal. I mean. Then show them how functions can be called with function pointers and tell these are called callbacks. But with callbacks. The first one is. With callbacks. And to send functions as arguments. these steps can be followed. And other benefits are actually child of this one. Now.feedback For teaching callbacks. The functions which takes other functions as input arguments. the question is. you have to teach the pointer first. Then the input signal resolution and execution of corresponding code become much easier. There might many more things. we need callbacks. Once the students understand the idea of pointer to a variable. you can make an array. Hope this helps. functions also have addresses or pointers. If we pass the function a doubling callback. answered Mar 13 at 18:31 Gulshan 500 6 19 1 My another answer related to this topic in programmers. a linked list or use them with other data like in dictionary of key-value pairs or trees. An example can be a function which take an array and a callback. So. Then tell them how executable code or functions are just like some other data(or variables) in the memory. we get squares. . why all these hassle for calling some functions? What is the benefit? Like data pointers. idea of callbacks will get easier. This is a powerful benefit. function identifiers or function names cannot be used as normal data. Involve the students and they will discover.com/a/75449/963 – Gulshan Mar 13 at 18:34 feedback http://stackoverflow.. function pointer aka callbacks has some advantages over using normal identifiers. a dictionary can be maintained to map signals with callbacks. If we pass a squaring callback.. Then teach them there are things that can be done only with pointers(like passing a variable by reference). answered Mar 14 at 2:27 pete 21 1 feedback http://stackoverflow. When you call a function.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. that is like sending a letter. ..A callback is a self-addressed stamped envelope. If you want that function to call another function you provide that information in the form of a reference or address.. character strings. # Perlistas note: I know the sub doesn't need a name. You don't know when or if grabDBValue will return. I could easily change the behavior of the program by doing this: grabDBValue( (lambda x: passToLogger(x) )) Callbacks work well in languages where functions are first class values. is simple and concise. I pass in an anonymous function (or lambda) that sends the value to a GUI window. so it accepts a function. answered Mar 11 at 3:57 gatlin 89 5 +1. grabDBValue( (lambda x: passValueToGUIWindow(x) )) grabDBValue could be written to only grab a value from a database and then let you specify what to actually do with the value. booleans. for example.. just like the usual integers. you can "pass" a function around by passing around a pointer to it and the caller can use that. I actually quite like this answer. in Java. In C. this is for illustration $val in this case will be 6 because the callback has access to the variables declared in the lexical environment where it was defined.. . and you tell her "Call me when you get home so that I know you arrived safely". Lexical scope and anonymous callbacks are a powerful combination warranting further study for the novice programmer. etc. – TarkaDaal Mar 16 at 10:08 feedback A metaphorical explanation: I have a parcel I want delivered to a friend." really) outside of classes. Here.Imagine a friend is leaving your house. You want some procedure to pass control back to you when it has completed some task. the caller will ask for a static class of a certain type with a certain method name since there are no functions ("methods. http://stackoverflow. The explanation of what a callback is. and in most other dynamic languages you can just pass a function with simple syntax. and I also want to know when my friend receives it. I have two options: (a) I can wait at the post office until it is delivered. In Python. regardless of language. If I want to know when my friend receives the parcel. that is (literally) a call back. }). but if/when it does. you know what you want it to do.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. Protip: In languages with lexical scoping (like Scheme or Perl) you can pull a trick like this: my $var = 2. So I take the parcel to the post office and ask them to deliver it. so you give it a function to use to call back to you. That's what a callback function is. my $val = someCallerBackFunction(sub callback { return $var * 3. answered Mar 16 at 16:36 yunzen 4. but he does http://stackoverflow.the first function calls back into the context from where it was called. which function should be called by the function from outside B. he doesn't always understand notations.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. Usually it is called when some operation is completed.007 1 8 21 feedback I think it's an rather easy task to explain. And the further is. That is all. that we call this function (let's call it A) from inside another function (let's call it B). answered Mar 11 at 4:23 tonylo 1.. so that it can call it. Since you create the callback before giving it to the other function. At first callback are just ordinary functions.420 1 10 29 feedback Think of a method as giving a task to a coworker. That is why it is named a call*back* ..638 2 13 19 feedback Plain and simple: A callback is a function that you give to another function. answered Mar 14 at 16:34 Andrei Vajna II 1. At the time I call function B I also tell this function to call function A.(b) I will get an email when it is delivered. you can initialize it with context information from the call site. The magic about this is that I decide. At the time I write the function B I don't know which callback function should be called. such as ^ . A simple task might be the following: Solve these equations: x + 2 = y 2 * x = 3 * y Your coworker diligently does the math and gives you the following result: x = -6 y = -4 But your coworker has a problem. Option (b) is analogous to a callback. . “Run myfunction() every 10 seconds for 5 times” Or you can create a function directory.understand them by their description. If you pass the pointer (address) of a function as an argument to another. and you will call that function under certain condition. http://stackoverflow.” Lets look at a simple function pointer example void cbfunc() { printf("called"). you write a callback timer. you just add the following to all of your instructions: If you have any questions about symbols. And he has difficulty remembering your tips as well. For example. /* perform callback */ callback(). callback fail() if failed. “Callback success() if success. rather than giving you a bad response and making the process restart.459 8 30 feedback What Is a Callback Function? The simple answer to this first question is that a callback function is a function that is called through a function pointer. It allows you to specified the duration and what function to call. such as just ask me. answered Mar 16 at 22:06 Guvante 6. He always follows your written directions as best he can however. Everytime he finds one of these you get back the following: I don't understand "^" This requires you to rewrite your entire instruction set again after explaining what the character means to your coworker. Callback function is hard to trace. /* point to your callback function */ callback=(void *)cbfunc. Such as exponent . when that pointer is used to call the function it points to it is said that a call back is made. return 0. but sometimes it is very useful.. Callback function is like asking your user to gives you a function name. } int main () { /* function pointer */ void (*callback)(void). and the function will be callback accordingly. Especially when you are designing libraries. passing a list of function name and ask the library to callback accordingly. You think of a solution. call me at extension 1234 and I will tell you its name Now whenever he has a problem he calls you and asks. . and he doesn't always remember in between questions..com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. }myst.where function2 executes some code and returns a variable back to the initial function . function2(var2) ) This is one type of callback . answered Mar 7 at 5:30 Nishant 365 2 11 feedback http://stackoverflow. void cbfunc(myst *mt) { fprintf(stdout.} How to pass argument to callback function? Observered that function pointer to implement callback takes in void *. Suppose you have task where the variable needs to be processed before being given as an argument . typedef struct myst { int a.b. //param myst m. Therefore you can pass in multiple arguments by structure.mt->a. . /* point to callback function */ callback = (void*)cbfunc. /* perform callback and pass in the param */ callback(&m). } answered Mar 26 at 10:04 Sachin Mhetre 1. which indicates that it can takes in any type of variable including structure. } int main() { /* func pointer */ void (*callback)(void *). return 0. function (var1 .com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o.mt->b). m."called %d %s.". char b[10].you can use callback ..a=10.849 1 7 26 feedback Usually we sent variables to functions . What if I want var2 to be processed and then sent as an arguement ? function (Var1 . var2) is the usual way ."123").. strcpy(m. filter([1. in javascript. } http://stackoverflow. doA(result).github.. You gain flexibility and customizability while being able to have more maintainable code. } Later you want the exact same function to call doB instead you could duplicate the whole function: function computeB(){ . doB(result).js...com/underscore/#filter answered Mar 11 at 3:40 letuboy 155 4 feedback Imagine you need a function that returns 10 squared so you write a function: function tenSquared() {return 10*10. function(num){ return num % 2 == 0. you could find all even elements in an array like this: var evens = _.} Later you need 9 squared so you write another function: function nineSquared() {return 9*9. 4. You have a function that does something and when done calls doA: function computeA(){ .js: http://documentcloud.. Less hardcode = easier to maintain and change = less time = more business value = awesomeness.} The exact same thinking applies for callbacks... . 2. using Underscore.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. 6] Example courtesy of Underscore. 6]... For example. that modifies or adds to the behavior of that other block of code to suit your needs. }).} Eventually you will replace all of these with a generic function: function square(x) {return x*x.Callbacks allows you to insert your own code into another block of code to be executed at another time. 4. => [2. callback(result). 3. 5. } Or you could pass a callback function as a variable and only have to have the function once: function compute(callback){ . similar to when you call someone on the phone and leave a callback number.. your result function (callback) is called and you can handle the data.408 1 7 20 http://stackoverflow.com. If you write your program using callbacks. answered Mar 11 at 4:00 Brian Nickel 3." This allows the UI to still allow user interaction while the file is downloading. Once the webpage has finished downloading..Then you just have to call compute(doA) and compute(doB). it allows you to request something and continue executing while waiting for the result. Basically.google. Once the result comes back to you via a callback function. you can pick up the operation where it left off. . answered Mar 11 at 4:07 sokket 36 4 feedback [edited]when we have two functions say functionA and functionB. If you write your program synchronously. then we call functionB as a callback function. you request the data and say "execute this function when you've finished. it lets asynchronous code let you know it has completed by calling your arbitrary function on completion. the function you write to download the data will be running continuously until all the data is download. edited Mar 12 at 4:31 answered Mar 7 at 5:56 Balaswamy vaddeman 1. Beyond simplifying code.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o. This means your UI will not refresh and will basically appear frozen.790 1 6 17 feedback This of it in terms of downloading a webpage: Your program runs on a cellphone and is requesting the webpage http://www.if functionA depends on functionB.this is widely used in Spring framework. http://stackoverflow. ..com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o..feedback Not the answer you're looking for? Browse other questions tagged function callback or ask your own question.
Copyright © 2024 DOKUMEN.SITE Inc.