Delay ajax request by x seconds and update only the last clicked request
Hi all I am delaying a AJAX request by 3 seconds and then updating a div with the response. But the problem what I face is, when the user clicks on all the three links simultaneously, the requested content keeps getting updated in the div. What i am trying to do is开发者_运维百科, serve only the last clicked ajax request content, but should not abort the previous requests too. Is there any way that i can achieve it ?? Thanks in advance
Script
$('.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
<ul>
<li><a href="http://localhost/test.php">Link 1</a></li>
<li><a href="http://localhost">Link 2</a></li>
<li><a href="index.html">Link 3</a></li>
</ul>
You're going to need:
- A way to clear the last timeout registered, and...
- A way to cancel the asynch success function in the event the timeout event was not cleared before the asynch request was made
For the first item, timeout function calls can be cancelled by using clearTimeout() with the ID returned by setTimeout()... pretty straightforward. As to the second point, you can do this by timestamping every call and comparing the value of the timestamp variable enclosed by your success function against the timestamp of the last click call made.
See below:
// 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) };
});
精彩评论