将ajax请求延迟x秒并仅更新最后一次单击的请求

大家好,我推迟了一个AJAX请求3秒,然后用响应更新div。 但我面临的问题是,当用户同时点击所有三个链接时,请求的内容会在div中不断更新。 我想要做的是,只提供最后点击的ajax请求内容,但不应该中止以前的请求。 有什么方法可以实现吗? 提前致谢

脚本

$('.links li a').click(function(event){ event.preventDefault(); var getUrl = $(this).attr("href"); var printCall = function() { $.ajax({ url: getUrl, type: "GET", beforeSend: function() { }, error: function(request){ alert(request) }, success: function(data) { $('#graphContent').html(data); } }); }; setTimeout(printCall, 3000); }); 

HTML

  

你需要:

  • 清除注册的最后一次超时的方法,以及……
  • 在asynch请求发出之前未清除超时事件的情况下取消异步成功函数的方法

对于第一项,可以通过使用带有setTimeout()返回的ID的clearTimeout()来取消超时函数调用…非常简单。 至于第二点,您可以通过为每个调用加时间戳并将成功函数包含的timestamp变量的值与最后一次单击调用的时间戳进行比较来实现。

见下文:

 // A tracker object outside the scope of all click functions var pendingCall = { timeStamp: null, procID: null }; $('.links li a').click(function (e) { e.preventDefault(); var getUrl = $(this).attr("href"); // A timestamp for this call var timeStamp = Date.now(); var printCall = function () { $.ajax({ url: getUrl, type: "GET", beforeSend: function () { }, error: function (request) { alert(request) }, success: function (data) { // Short-circuit execution if the timestamp on this call doesn't match the last one made if (pendingCall.timeStamp != timeStamp) { return false; } // The action to take $('#graphContent').html(data); // Clear the reference to this timeout call pendingCall.procID = null; } }); }; // Clear the timeout on the last call made if it exists if (pendingCall.procID) { clearTimeout(pendingCall.procID) }; // Update the timeout call tracker pendingCall = { timeStamp: timeStamp, procID: setTimeout(printCall, 3000) }; });