Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript jQuery call backs vs chaining. When to use what?

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #186244
    vgvenkat
    Participant

    I am now a little confused with chaining and call back functions. :-/ . Both have the “do this, on completion do the other thing” kinda vibe. how do you differentiate when to use what? . Is callback function more like heavy duty chaining?

    I find chaining to be most used in small doing changes like change color or find elements and apply property and stuff. Can any one elaborate please?

    #186246
    __
    Participant

    It’s not quite as straightforward a question as you seem to think. It generally has more to do with how the function is written than what it does.

    Chaining is when you call a method on an object, the method does something, and then returns the original object. It literally is like a link in a chain.

    object--→method--→does something--┐
       ↑                              |
       └---returns original object----┘
    

    Callbacks are like (upside-down) trees. You give the function another function, with the expectation that the original function will call your function at some point (often, when done, but this is not a requirement).

    function(callback)--→does something
                              └--→calls callback
    

    jQuery does mainly chaining.

    Javascript, in general, is very well-suited to using callbacks.

    You may have heard of “promises”, the syntax of which looks like chaining, but is actually a pattern of managing callbacks.

    #186332
    vgvenkat
    Participant

    I did some digging around and I found out callbacks are more like queued up processes. Only on the completion of one, the next goes thorough while in chaining, if one takes some time to complete such (as animations), the next process could execute before completion.

    #186344
    __
    Participant

    found out callbacks are more like queued up processes. Only on the completion of one, the next goes thorough …

    Maybe. In most cases, people write their functions so that the callback is executed at the end, after everything else is done. This is by far the most common usage. But it is not required to work this way —the callback can be called at any point during the function execution.

    if one takes some time to complete such (as animations), the next process could execute before completion.

    This is because javascript is asynchronous. functions start when they start, and end whenever they end. : ) In most cases this is really useful and efficient, but it is different than what you might be used to with other languages.

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.