Morgan Green Morgan Green - 6 months ago 12
jQuery Question

Make Jquery function wait for previous function

I'm trying to set up a feed that loads every five seconds. I've got the first part to work where it loads while you're just sitting on the site. My next issue now is that it just pops up suddenly, so I'm trying to get it to look smoother.

function FinalizeFeed(result) {
$(".useractivity").html(result);
}
function LoadFeedData() {
var dataString = "action=loaduserfeed";
$.ajax({
type: "POST",
url: "/core/functions.d/feed.php",
data: dataString,
cache: false,
success: function(result){
$(".post-loading").html('<center><i class="fa fa-circle-o-notch fa-spin fa-5x fa-fw"></i><span class="sr-only">Loading...</span></center>').fadeOut("slow");
setTimeout(FinalizeFeed(result), 2000);
}

});
}


So my thought was create the
FinalizeFeed
function. Works fine, but still just pops up. If I don't add the Finalize function under the
.post-loading.html
the spinner shows up and looks real nice, but doesn't really help with loading new data in. with the setTimeout I thought it would wait, but the spinner doesn't even show up. Does anyone see what the issue is with this code?

Answer

Don't delay the result response. Even by 2 seconds. You don't actually want spinners and loaders showing, as that indicates slow-loading data. If /core/functions.d/feed.php fires and sends a response in 100ms, why wait an additional 1900ms to display it?

By adding your spinner/loader to beforeSend, the spinner fires on the initial $.ajax() call, and is removed once the operation is complete.

So in removing the setTimeout() the data is returned, and displayed, once it is available. Once the operation is complete, the spinner is removed.

Aside: All to often I see people delaying responses just to have a flashy spinner showing. Users want data, not spinners.

function LoadFeedData() {
    var dataString = "action=loaduserfeed";
    $.ajax({
        beforeSend: function() {
            $(".post-loading").html('<center><i class="fa fa-circle-o-notch fa-spin fa-5x fa-fw"></i><span class="sr-only">Loading...</span></center>').fadeOut("slow");
        },
        type: "POST",
        url: "/core/functions.d/feed.php",
        data: dataString,
        cache: false,
        success: function(result) {
            $(".useractivity").html(result);
        },
        complete: function() {
            $(".post-loading").html('');
        }
    });
}

By removing FinalizeFeed() you're now streamlining your code. That function is tightly coupled into your $.ajax() success function, so it's not actually reusable, and therefore, not worth creating.

Comments