146 responses to “Understanding callback functions in Javascript”

  1. Muhammad Ghazali

    Hei, your article is interesting. I’ve got insight after read this and know a lot more than before about callback function, specifically in JavaScript.
    I did not know that if the function in JavaScript are objects, so I’m glad to know that.
    Thanks :-)

  2. Uli

    AH! AAAAH! I was searching for a tutorial about callbacks, why they are used and what for. I guess I understood a little bit more now. Thanks!

  3. kiat

    Great tutorial, I was looking to implement a callback function and now I can try it.

  4. sami

    thanks so much for this. i’ve been searching for a while on a tutorial or an article of sorts to clear up callbacks for me, and this was it. you definitely were not kidding when you said there was nothing out there. thank you!

  5. Sarah-Jane

    Thanks! You made it so clear

  6. PandeySrivastav

    Hello Everyone,
    We can create function in Java Script to perform some specific task when needed. We can use function in java script to keep some scripts inside it and is used to perform an action on the click event of any object. We can use function keyword to create function in java script………. for more details check this link…… http://mindstick.com/Articles/0864994b-563d-4180-87bd-b6e3bea77c26/?Function%20in%20Java%20Script

    Thanks !!!!!

  7. Sidney

    very clear! thank you.

  8. rogical

    good js project to solve serial callback functions
    https://github.com/JacksonTian/eventproxy

  9. Techie Salsan

    Callback methods are widely used in Jquery. It will solve the issue browser freezing while running long scripts.. Anyway thanks for the article.

    1. maxw3st

      How does it solve the browser freezing issue? Could you give an example. I ask because having Firefox get frozen while running JavaScript and jQuery seems to be a common occurrence when opening web pages these days. I’d like to be able to run some code to unfreeze it.

  10. v9

    Nice one …keep it up

  11. SirBertly

    Wow! I love this article!! I love you!!! Thanks a lot man! I’ve been using callbacks rather unconfidently, this really helps explain it!

  12. Blanka Bouskova

    Thank you very much!

  13. Jannik Olsen

    Hiya,

    thanks for the article, that cleared up the subject for me, allowing me to properly sequence my functions in collaboration with jquery queue/dequeue functions. Actually, it made the task stupidly simple.

    Seeing as I’d been browsing the net for a solution, finding a jqeury plugin for sequencing functions which I scrapped as being too convoluted, I’m *very* pleased to finally be able to use the callback aspect of js. The concept is familiar as jquery uses it all the time – I’ve just been clueless as to how I can use it myself :)

    As an aside: if you want the callback parameter to be optional you can do a simple ‘if’ in your function:

    if(typeof(callback) === ‘function’)
    callback();

    //Jannik

    1. Christopher Engle

      Not only can you check for typeof === ‘function’ but if it’s exists at all. If undefined then use normal return.

      e.g.

      if ( callback && typeof callback === ‘function’ ) {
      callback.call( this, value );
      } else {
      return value;
      }

      This is roughly how jQuery().html() works and speaking of jQuery, this is how chaining is accomplished for functions that must return a value.

      example:
      var foo = {
      bar1 : function() {
      // do something
      return this; // continue the chain
      },
      bar2 : function( fn ) {
      // do something
      fn.call( this, returnValue );
      return this;
      }
      }

      foo.bar2(function( returnValue ) {
      // alert returnValue
      }).bar1();

  14. Gaurav Thakur

    Very clear@@@@ Was useful and understood it now :)

  15. Aswin

    Thanks ! That was just what I wanted. I’ve walked on the same route of being a C/Java/PHP dev and I’ve always found it confusing to use callbacks (Though I manage to pull out code with callbacks). I guess it is just a mindstate that fails to comprehend the concept of callbacks and closures.

  16. Chris

    The first time I read this article I don’t understood it fully because I was at the beginning of js but now it all makes sense :) thank you very much

  17. Snin

    how can we return a value from a callback function and collect it?? thanx in advance.. :)

  18. Sebi

    Thanks a lot for this article! It made my JavaScript-Day :)

  19. zippy

    Nice article – clear, brief and concise :-)

  20. kaplan

    Thanks so much for the clear explanation and example!

  21. Edox

    Thanks for the article, but i have a question
    Why when I run callback functions, func1 is waiting finish func2.

    function func1(arg1, cb1){
    var my_var = arg1;
    cb1(“func1 ready with “+my_var);
    }
    function func2(arg2, cb2){
    var acc = 0;
    for(k=1; k < arg2; k++){
    acc = acc+k;
    }
    cb2("func2 ready with "+acc);
    }

    //Call functions
    func2(100000000, function(resp2){
    console.log(resp2);
    });

    func1(5, function(resp1){
    console.log(resp1);
    });

    Thank again.

    1. Edox

      Hi again if I put in func2 SetTimeout this is run ok for my, but I dont understand why. can someone help me please.

      function func1(arg1, cb1){
      var my_var = arg1;
      cb1(“func1 ready with “+my_var);
      };
      function func2(arg2, cb2){
      var acc = 0;
      setTimeout(function(){
      for(k=1; k < arg2; k++){
      acc = acc+k;
      };
      cb2("func2 ready with "+acc);
      },0);
      };
      //Call functions
      func2(100000000, function(resp2){
      console.log(resp2);
      });

      func1(5, function(resp1){
      console.log(resp1);
      });

      1. Shihab

        Excellent Job.

  22. Node.js: Links, News and Resources (4) « Angel “Java” Lopez on Blog

    [...] Understanding callback functions in Javascript http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]

  23. Morph

    Excellent beginner’s tutorial to callback functions. Thanks for posting this. If you uncover any other Javascript gems worth explaining, I’ll be back to read ‘em!

  24. Using tail recursion | Recurial

    [...] article on callback functions worked out pretty well and got a positive reaction, so I’m going to continue with the theme [...]

  25. velocidad

    Hey, thanks for the article, that was very useful and easy to understand :D

  26. nK0de

    I recently started learning JavaScript on my own. And I’ve been seeing a lot of callback functions in code examples. I searched the web for a decent tutorial on callback functions but to no avail. Until I came across your blog. I think this is the only tutorial on callback functions. Thank you very much and it is very helpful. Cheers!

  27. Ranu Mandan

    its nature of callback function to be asynchronous … it does not block control flow while running.

  28. Node.Js: Links, News And Resources (5) « Angel “Java” Lopez on Blog

    [...] Understanding callback functions in Javascript http://recurial.com/programming/understanding-callback-functions-in-javascript/ [...]

  29. anson

    Hey thanks for writing this article. Its the clearest tutorial on js callback functions out there :)

  30. Simon Slangen

    Thank you for the comprehensive article. Started on JS yesterday, and although progress is fairly quick, things like this are completely new to me.

  31. manoj

    hey your page was awesome man … i mean i got the jist of it but …. however could you explain it without ajax…then i guess it would be pretty much simple for those who dunno ajax(me)…:-)

  32. Mick

    Great article! Really clears up callbacks… They are so dead straightforward really :-)

    1. Mick

      You should follow up with a similar style article on prototypes – then do closures!

  33. André

    Thanks man

  34. anuradha

    Very simple and clear article on callbacks.

  35. Anna

    Very solid article on callback functions. They make a lot more sense to me now.

  36. Mike

    Brilliant and simple explanation. I use them all the time but now I understand why!

  37. Mark

    Thanks for this it was really useful for me!

  38. Shamal

    Thanks Mate… Good one.

  39. Chad

    YOU ARE THE MAN!! I’m pretty new to all of this, and only a few weeks old when it comes to .js. Last time I wrote a single line of code (before I started this project), was before basic had a colored screen, and objects only existed in the real-world!

    I’m trying to tidy up the code, now that the race to roll-out is over, and have a ton of code that is essentially duplicated everywhere. A few selector changes allowed me to reduce each block by 75%, and put it in one named function, to be used across the application, but I haven’t been able to get it to return the output object. I spent the better part of the last 24hours, and 50 iterations, looking for an answer, and only found a headache! I’m still not sure why I couldn’t return normally, or why this worked, but I barely had to change what I had left last night, and POW!

    I feel like I owe you a drink or something! THANKS!

  40. How to run a function only after directionsDisplay ends? | PHP Developer Resource

    [...] my code I did the following, using patterns from Recurial and JavaScript Callback after calling [...]

  41. Harnessing Client-Side Technologies to Enhance your SharePoint Site « SPMatt

    [...] Leverage callbacks [...]

  42. kyle

    Thanks! That was nice, to the point, and needed!

  43. 70-480 - Programming in HTML5 with JavaScript and CSS3

    [...] Loop JavaScript Try…Catch Statement JavaScript Throw Statement Scope in JavaScript Understanding callback functions in Javascript Getting comfortable with Javascript callbacks THE BASICS OF WEB WORKERS Introducing HTML5 [...]

  44. Milan

    This one is going into my bookmarks. Thank you

  45. callback function in javascript | myrubylearning
  46. Jeff

    Excellent article thanks for taking the time to put it together.

  47. Lizzie

    console.log(“this will run before the above callback”);
    // this line did the work :-)

  48. Cedik

    Very helpful! I noticed a callback used inside a script found on the web and I was wondering what it meant and now I know :D

    I have very little experience with Java or C, but to me this resembles a bit (but just a bit) to Objective-C’s multithreading techniques, at least on the asynchronous part. There I used to run a method that was doing some heavy computation on a background thread, like parsing an XML in your example, and call a function to update the UI when it finished. I guess the principle is similar

  49. islam

    I was wondering about this concept, thanks a lot , your article enlightens my way!

  50. Andrew Shatnyy

    If coming from ruby, callbacks are more like “lambdas” or “procs” which makes function an object.
    Thanks it’s all clicked now :)

  51. NodeJS « Adventures : )
  52. Node.js | MY KNOWLEDGE LIBRARY
  53. Sam

    Thank you so much!
    this was exactly what i was looking for,
    good job!!

  54. Gilang

    Easy and right to the point.
    Thanks for the explanation man. Definitely helpful. :)

  55. YatharthROCK

    Great article! JS is _weird_. It is just too… unstructured. Which is kinda cool. Do you have any more articles like this? JS is multi-threaded, right?

    Circle me on Google+: https://plus.google.com/115093555862694271963/about/
    Follow me on Twitter: https://twitter.com/YatharthROCK

  56. DracisFL

    // Internet Explorer is stupid

    Ha Love that comment..

    Thanks for the article, very insightful.

  57. Exame Microsoft 70-480 – Programming in HTML5 with JavaScript and CSS3 « Leonardo Trindade

    [...] Understanding callback functions in Javascript [...]

  58. Jen

    Thanks so much for this. I was struggling with callbacks and you explained it perfectly.

  59. Mohsin

    Hello Mike!

    Thank you for sharing an awesome article on callback functions… Now I am able to write code with callback functions…

    Thank you so much!!!

    Mohsin

  60. Hittesh Ahujah

    Hey
    Really good article on callbacks….cheers!

  61. zeb

    FINALLY!!!! I was staring to think callbacks were a closely guarded secret or something!
    So much for me is cleared up in your last paragraph:

    “… the second console.log statement will run before the first, because the callback isn’t executed until the request is over, and UNTIL THAT HAPPENS THE REST OF THE CODE GOES RIGHT ON AHEAD AND KEEPS RUNNING.”

    Thanks so much for taking the time to do this, and I hope you do more of these! My only small ‘nark’ here is that you fell into a classic developer habit – only explain what you’re explaining, nothing more. Don’t get distracted by browser compatibility or “.call()” etc… These things are cool, but aren’t in scope with what you’re explaining and just add complexity.

  62. bolaru

    Anyone checked async/await in .NET 4.5? They seem to be a better pattern for asynchronous programming then callbacks. Unfortunately they are not available in JS.

  63. Wayne Kenneth Seymour III

    Thanks for the info, seriously.
    Yet, like you, I’ve been writing non-async code too long.
    My mind is not ready for async still! lol

  64. 70-480 Exam Preparation Guide | The SharePoint Viking

    [...] messages from the HTML5 WebSocket API Use jQuery to make an AJAX call Wire up an event Implement a callback by using anonymous functions Handle the “this” [...]

  65. http://recurial.com/programming/understanding-callback-functions-in-javascript/ « kwangz – space

    [...] Subscribe to RSS December 10, 2012   [...]

  66. Jiehan Zheng

    Thank you very much for writing this article! Made me instantly able to write my own callback handler…

  67. callback functions in Javascript « rg443blog

    [...] Understanding callback functions in Javascript. [...]

  68. mahmoud

    thanks

  69. zeb

    Mike – quick question for you …
    I keep seeing functions represented as ‘callback’ functions in this way:

    x = function() { return $(“iframe”).attr(“src”); };

    … what’s the advantage of this over the ‘standard’ way:

    function x() { return $(“iframe”).attr(“src”); };

    … or even just:

    x = $(“iframe”).attr(“src”);

    ?? It doesn’t wait for the iframe to be present (so it’s not doing anything ‘asynchronously’ … or is it?).

  70. Jason

    Great Post.

  71. Andrew Henderson

    Excellent post, Mike.
    The examples you gave couldn’t have been better. I’ve been wanting take advantage of callbacks in my custom functions beyond jQuery. This article really helps shed light on the subject.

  72. Dejan

    Thank you, after I read your post I found what I was doing wrong.

  73. Exam 70-480 Programming with HTML5, Javascript and CSS3 Study Guide | The SharePoint Viking

    [...] messages from the HTML5 WebSocket API Use jQuery to make an AJAX call Wire up an event Implement a callback by using anonymous functions Handle the “this” [...]

  74. jason

    thanks a lot! this is exactly what i was looking for.

  75. Understanding callback functions in Javascript | Avant Mobile

    [...] Understanding callback functions in Javascript. [...]

  76. Uma

    Fantastic explanation! Thanks for this article.

  77. Andy

    Thanks a lot.

  78. aflext

    Thanks a lot. We can assume the ‘callback’ function as an assistant of our working function because an assistant is to help us do something.

  79. Imran shaikh

    Excellent Stuff, I appreciate the way to make “callbak” function understanding in a very simple language very much helpful to understand the concept .. good job keep it up Dude! …

  80. JavaScript Callback Functions - The Absolute Basics | Kevin Chisholm - Blog
  81. Andy

    Thanks for taking the time to write this out, although I have programmed with JavaScript, I come from the more traditional paradigm.

    It then leaves other questions in my head like… that means you can’t know what it is doing when the callback is running, and asynchronous anarchy :)

    Cheers

  82. Madusha

    Thanx :)

  83. PMana

    Thanks! from java/c++ this is probably the best explanation i got.

  84. Mihail Ivanov

    Really helpful, thanks! :)

  85. Unknown

    try to improve your tutorial

  86. Rakesh

    Thanks a ton!

  87. Andrew Ingram

    This is important, callbacks are *not* asynchronous. AJAX callbacks are asynchronous, because AJAX itself is asynchronous, but callbacks in general are *not*. So callbacks don’t mean your code is non-blocking.

    If you want to do true asynchronous (and therefore non-blocking) code in javascript you need to use web workers, which aren’t supported in IE9 and below:

    http://caniuse.com/webworkers

    1. Andrew Ingram

      I should add, user interaction events such as clicks, scrolling etc, as well as timer calls like setTimeout actually *are* asynchronous, but there are some caveats:

      http://ejohn.org/blog/how-javascript-timers-work/

  88. Felipe Marcellino

    Very comprehensive!

  89. takı

    Great Post, helped us to figure the details out

  90. Ibrahim Islam

    Nice one, bro :D

  91. Simone

    Hey, thanks! I finally got it.

  92. Serkan Sipahi

    thnx, best example ever :)

  93. Mohammed

    thanks

  94. dibish

    This tutorial is really awesome…thanks for the post

  95. Gregory

    I cant explain how grateful I am to finally understand the mystery behind these callbacks. This has opened up a new world of javascript for me.

  96. Mohsen Nemati

    Thank You Realy Much :X

    It Was Great

  97. Callback Functions | Cat's Web Dev Blog
  98. Callback Functions | Cat's Web Dev Blog
  99. Callbacks in Appcelerator Titanium Modules « Appcelerator Developer Center

    [...] the end, what I wanted to implement was a JavaScript-ish callback associated with a native App47 Agent call. Alas, it took me a lot of digging to achieve this [...]

  100. How callback functions in JavaScript work | No strong beliefs
  101. Janet

    Thank you so much and now I see how callback works!

  102. Entendiendo la importancia de las llamadas Callback | Appcelerator Canarias

    [...] Understanding callback functions in Javascript (en inglés by recurial.com) [...]

  103. CodePozol — Guía de estudio 70-480 Programming with HTML5, Javascript and CSS3

    [...] messages from the HTML5 WebSocket API Use jQuery to make an AJAX call Wire up an event Implement a callback by using anonymous functions Handle the “this” [...]

  104. Anthony

    Thanks so much for this! Very informative :)

  105. Code Guru

    Nice article. Gives a good overview on call back functions to get be started. I definitely agree with you on the ‘Spaghetti’ remark. :)

  106. Jonathan Tien

    This article is the first DECENT article ON delegates and callbacks I have come across which MAKES SENSE!!!!

    Keep writing. You rule.

    JTN

  107. Scott

    Just to clear up something about your intro that I found misleading, the .apply() & .call() methods have nothing to do with “callbacks” per se in JS. There are meant to be used to situationally apply scope. You very briefly went over this, but I felt it was worth noting.

  108. Kristian

    A very well-written article; keep up the excellent work!

  109. My terribly unordered unordered lists | Frontfacing - A blog about Frontend Development, TYPO3 and Me

    […] Understanding callback functions in JavaScript Link […]

  110. Anas Azeem

    **Thank You**

  111. ranadheer

    very clean and easy explanation about callbacks. thanks for the article.

  112. Alfred Nutile

    Thanks!

  113. Arvie

    Hey, just another “thanks” for your very clear, concise and well crafted tutorial. Really helped!
    RV

  114. JS: Tìm hiểu về Callback trong JavaScript | Say sưa blog
  115. As Sabiluna

    really awesome example and explanation u have here. I become more understand about the nice thing about callback

  116. HTML Actions vs Javascript Callbacks | Powers Coding - Snippets of code I found useful
  117. Jaco Pretorius

    Nice article, I always enjoy confirming that I got all the basics right.

  118. Raffy

    Great work. Thank a lot :-)

  119. Live Streaming Κάλυψη Συνεδρείων
  120. Dirk

    Thank you for taking the time to write this article. I’m just now learning JS and the concept of a callback was new to me. Your explanation cleared it up – mainly that it is used to support asynchronous tasks.

  121. Using MongoDB with Kraken.js and Dust | Web Development In The Cloud
  122. Callback Mountain – straight up asyncronous | Learning code

    […] How is this possible? Functions in JavaScript are objects created with the Function constructor. The object contains a string. This string is the code of the function. Or something. […]

  123. Gyan

    Nicely composed

  124. Piotr

    Hi,

    Thanks for this article – it was extremely helpful for me to understand callbacks. I actually do not come across this construct very often. Today it’s actually the first time when I was forced to use it. I was creating a custom callback function for jq boostrap validation – never did it before so started digging for answears.

    Like you, I’m more of a Java/C++ “thinker”. Still, I just got something like a epiphany (positive stroke) after reading this :) SO MANY OPTIONS

  125. How I Learned to Code in 1 Year | Living For Improvement

    […] example, the Chrome extension framework relies very heavily on callback functions, which I had a hard time wrapping my head around as a beginner. The difficulty in grasping tricky […]

  126. Kuei-Ti Lu

    Thank you for this article.

    The first time I encountered a callback function in JavaScript, it was a complicated one, which was not a good example for learning callback functions (it was used to learn something else). This article clarifies how callback works in JavaScript for me.

  127. Imran

    Function as an object ! interesting

  128. Can't understand this javascript code with callback and async | Stackforum.com
  129. Gerrit

    Now I understand the callback function, thank you so much!

  130. Amir

    Thank you for this awesome tutorial. I have been trying to understand the difference between return and callback and with simple example that you took in the code cleared my understanding totally. Now I understand the difference between return and callback.

  131. Pulling JSON data from a public data API | Getting Unstuck

    […] the whole thing is wrapped in an IIFE, inside of that everything is wrapped in the callback function of an event handler attached to the button, so that all the code is triggered when the button is […]

  132. Dan

    This is the most amazingly simple explanation to a complicated subject I have ever seen. I wish you were my professor! -Thanks

  133. vasilis

    thanks dude

  134. web site

    Un post vraiment plein de bon sens

  135. Andre

    Thank you so much… Over 3 years old and this post still helped me understand callbacks better than virtually any other I’ve read through. :D Very nicely explained..

  136. abuzarhamza

    great explanation about callback.

  137. mam-p

    Super well-written explanation of JS callbacks! Thanks for writing!

  138. WebNinjaTaylor » JavaScript Callback Functions

    […] Understanding Callback Functions in JavaScript […]

  139. Geraldo

    Good work. Thanks for taking the time to write this.

  140. efkan

    Exactly!

    “They’re pretty much everywhere. Originally coming from a more traditional C/Java background I had trouble with this (and the whole idea of asynchronous programming), but I’m starting to get the hang of it. Strangely, I haven’t found any good introductions to callback functions online…”

Leave a Reply