Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do chained functions get executed in JQuery?

When a function is chained in JQuery, what is the order of operations?

Example 1

$(selector).fun1(val,{fun2(){ }}

Example 2

$(selecter).fun1().fun2().fun3() 
like image 759
Param-Ganak Avatar asked Feb 05 '10 12:02

Param-Ganak


2 Answers

From left to right. fun3() is run on the result (=return value) of fun2(), fun2() on that of fun1().

This kind of chaining can be done in JQuery because each chainable function returns the object/element it was called on.

So $(selector).fun1() returns the $(selector) element after execution. fun2() is called from that returned element, and so on.

like image 176
Pekka Avatar answered Sep 20 '22 06:09

Pekka


In this example:

$(selector).fun1(val,{fun2(){ }}

The second parameter to function one is a callback function. This means fun1 executes THEN fun2 executes.

In this example:

$(selecter).fun1().fun2().fun3()

All functions are fired off as quickly as possible if they have a duration, like say an animation. Otherwise they execute in order fun1, fun2, fun3.

So with animations, fun1, fun2 and fun3 would be 3 simultaenous overlapping animations, but with other synchronous operations, they simply happen in order.

like image 27
Nick Craver Avatar answered Sep 21 '22 06:09

Nick Craver