Page 170 - JavaScript
P. 170

foo(array, function (x) {
             console.log(x);
         });




        Examples with Asynchronous Functions




        In jQuery, the $.getJSON() method to fetch JSON data is asynchronous. Therefore, passing code in
        a callback makes sure that the code is called after the JSON is fetched.

        $.getJSON() syntax:


         $.getJSON( url, dataObject, successCallback );


        Example of $.getJSON() code:


         $.getJSON("foo.json", {}, function(data) {
             // data handling code
         });


        The following would not work, because the data-handling code would likely be called before the
        data is actually received, because the $.getJSON function takes an unspecified length of time and
        does not hold up the call stack as it waits for the JSON.


         $.getJSON("foo.json", {});
         // data handling code


        Another example of an asynchronous function is jQuery's animate() function. Because it takes a
        specified time to run the animation, sometimes it is desirable to run some code directly following
        the animation.

        .animate() syntax:


         jQueryElement.animate( properties, duration, callback );


        For example, to create a fading-out animation after which the element completely disappears, the
        following code can be run. Note the use of the callback.


         elem.animate( { opacity: 0 }, 5000, function() {
             elem.hide();
         } );


        This allows the element to be hidden right after the function has finished execution. This differs
        from:


         elem.animate( { opacity: 0 }, 5000 );
         elem.hide();




        https://riptutorial.com/                                                                             127
   165   166   167   168   169   170   171   172   173   174   175