callback to function after .each() has completed?

30,185

$.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).

Share:
30,185
user756659
Author by

user756659

Updated on July 16, 2022

Comments

  • user756659
    user756659 almost 2 years

    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                        
    }