Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

callback to function after .each() has completed?

Tags:

jquery

each

Not sure if this is possible or how to go about it. I am using the following in an $.ajax response which works perfectly fine, however, I need to call the function loadSlider(); AFTER the loop is finished iterating.

if (response.success)
{
    $.each( response.screenshots, function( index, value ) {
        //add the slide
        $( '#slider1' ).prepend( '<li data-id="'+value.screenshot_id+'"><img src="/showimage.php?show='+value.image_filename+'" alt=""></li>' );
        //add the pager
        $( '#rslides-pager' ).prepend( '<li><a href="javascript:;"># here</a></li>' );
    });

    //want to call loadSlider(); AFTER everything above is completed                        
}
like image 973
user756659 Avatar asked May 23 '14 06:05

user756659


People also ask

How do you call a function to run after another function is completed?

What is a Callback? Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name 'call back'. More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions.

How to create a call back function?

In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed.

When to use a callback?

A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard." button.

What is the need of callback function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.


1 Answers

$.each() iterates over the array synchronously, so you can simply run your code after the $.each(); call.

if (response.success) {
    $.each( response.screenshots, function( index, value ) {
        // do stuff
    });

    loadSlider();
}

As you mention AJAX: Only the actual success callback (i.e. the function that most likely contains the code you posted) is executed asynchronously. Any code inside that function runs synchronously (unless you call another asynchronous function in there of course).

like image 54
ThiefMaster Avatar answered Sep 22 '22 14:09

ThiefMaster