Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 1st, 2012  |  syntax: None  |  size: 1.82 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Delay ajax request by x seconds and update only the last clicked request
  2. $('.links li a').click(function(event){                        
  3.     event.preventDefault();
  4.     var getUrl = $(this).attr("href");
  5.     var printCall = function() {
  6.       $.ajax({
  7.         url: getUrl,
  8.         type: "GET",
  9.         beforeSend: function() {  },
  10.         error: function(request){ alert(request) },
  11.         success: function(data) { $('#graphContent').html(data); }
  12.       });
  13.     };
  14.     setTimeout(printCall, 3000);
  15.   });
  16.        
  17. <ul>
  18. <li><a href="http://localhost/test.php">Link 1</a></li>
  19. <li><a href="http://localhost">Link 2</a></li>
  20. <li><a href="index.html">Link 3</a></li>
  21. </ul>
  22.        
  23. // A tracker object outside the scope of all click functions
  24. var pendingCall = { timeStamp: null, procID: null };
  25.  
  26. $('.links li a').click(function (e) {
  27.     e.preventDefault();
  28.     var getUrl = $(this).attr("href");
  29.  
  30.     // A timestamp for this call
  31.     var timeStamp = Date.now();
  32.  
  33.     var printCall = function () {
  34.         $.ajax({
  35.             url: getUrl,
  36.             type: "GET",
  37.             beforeSend: function () { },
  38.             error: function (request) { alert(request) },
  39.             success: function (data) {
  40.                 // Short-circuit execution if the timestamp on this call doesn't match the last one made
  41.                 if (pendingCall.timeStamp != timeStamp) { return false; }
  42.  
  43.                 // The action to take
  44.                 $('#graphContent').html(data);
  45.  
  46.                 // Clear the reference to this timeout call
  47.                 pendingCall.procID = null;
  48.             }
  49.         });
  50.     };
  51.  
  52.     // Clear the timeout on the last call made if it exists
  53.     if (pendingCall.procID) {
  54.         clearTimeout(pendingCall.procID)
  55.     };
  56.  
  57.     // Update the timeout call tracker
  58.     pendingCall = { timeStamp: timeStamp, procID: setTimeout(printCall, 3000) };
  59. });