I had a recent issue with a dynamic page constructed in SharePoint using jQuery. The page had two functions. The first used SPServices to extract data from a SharePoint list. The second configured the jQuery ShowCase object to create a content slider based on the content extracted from the SharePoint list. However, while the content initially loaded, any button or link clink would clear the content, the ShowCase went blank.
I put some alerts into the code to find out what was happening and found that, if I had an alert at the end of each function, they worked. If I removed the alerts, it no longer worked.
What was happening here was that the alerts were giving enough time for one function to complete before the other started. The first function would fire, the alert would come up on the screen. This would give sufficient time for the data to return and then the ShowCase Function would fire on the completed content. But how to do this without alerts?
The answer was jQuery callbacks. This code forces the execution of each function in sequence, and, critically, does not fire the second function before the first has completed. Here is what that looks like:
var callbacks = $.Callbacks(); // create callbacks object
callbacks.add(getData); // add the data extraction function
callbacks.add(renderShowCase); // add the ShowCase render function
callbacks.fire(); // fire those functions in sequence.