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
}
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.
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.
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.
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.
$.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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With