user756659 user756659 - 6 months ago 27
jQuery Question

callback to function after .each() has completed?

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
}

Answer

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

Comments