- Delay ajax request by x seconds and update only the last clicked request
- $('.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);
- });
- <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>
- // 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) };
- });