jQuery:用最短时间完成处理程序

jQuery: complete handler with minimum time

本文关键字:处理 程序 短时间 jQuery      更新时间:2023-09-26

我有一个函数可以使用.load()加载内容(但它可以使用任何内容)。有时内容加载太快,以至于我使用的过渡动画看起来不太好,事实上这很令人反感。我想在转换之间添加一个最短时间,这样,如果内容加载得很快,它仍然会等待最短时间(比如500毫秒)。

我的代码目前看起来是这样的,有没有一种很好的jQuery方法可以做到这一点?

$("body").on("click","a[href]",function (e) {
    e.preventDefault();
    var href = $(this).attr("href");
    // Do pre load animation (removed for clarity)
    $("#rightpanel").load($(this).attr("href"), function () {
        // Do post load animation (removed for clarity)
        History.pushState(null, null, href);
    });
});

这里有一个涉及承诺的答案:

// suggestion 1
// wait for both pre-load animation and load to complete :
$.when(
    $('.gizmo').slideUp(),
    $("#rightpanel").load($(this).attr("href"))
).done(function(){
    $('.gizmo').stop().slideDown();
    History.pushState(null, null, href);
});

// suggestion 2
// add a "500ms promise" :
function delay(time) {
   var dfd = $.Deferred();
   setTimeout(function(){ dfd.resolve() }, time);
   return dfd.promise();
}
$.when( delay(500),  $("#rightpanel").load($(this).attr("href")) ).done(function(){
    //post load stuff
});

这是一把小提琴


正如Chris在评论中正确指出的那样,上面的代码将不适用于.load().load()应用于jQuery选择,并返回所选的集合,而不是底层的ajax promise。

如果使用$.ajax$.get$.post或其他全局jQuery函数,则上述代码将起作用,
或者你可以创建一个额外的承诺:

var loadData = $.Deferred();
$('#rightpanel').load($(this).attr('href'), function(){ loadData.resolve() });
$.when( delay(500), loadData ).done( ... )