如果jQuery.ajax等待响应足够长时间运行函数

我有一个jQuery代码,只是简单地发出一些ajax请求。

大多数时候获得响应所需的时间少于秒,因此我可以向用户显示结果。

但有时(大约5%的重新加载)需要几秒钟(我很好,服务器有点忙)。

我想在超过2秒的时间内显示“请稍候”文字。 但是当它花费不到2秒时(因此用户不会因快速显示/隐藏消息而感到困惑)。

如何以最有效和最简单的方式制作它?

当前的jQuery代码:

jQuery.ajax({ url: "loadData.php", dataType: 'json', type: 'GET', success: function(result){ showResultsToUser(result); } }); 

像这样的东西:

 var cancelMe = setTimeout(function() { $('#loading').show(); // assuming your loading element has the id "loading" }, 2000); // show loading element in 2 seconds jQuery.ajax({ url: "loadData.php", dataType: 'json', type: 'GET', success: function(result){ showResultsToUser(result); clearTimeout(cancelMe); // don't run if it hasn't run yet $('#loading').hide(); // hide the loading element if it's shown } });