$.ajaxDebounce({ delay: 100, ajax: getAjaxOptions() }) , event: '', element: null ajaxdebounce by ronency

ajaxdebounce

Download as .zip Download as .tar.gz View on GitHub

jQuery.ajaxDebounce.js

What?

ajaxDebounce is a jquery plugin that enables debouncing a function triggers ajax calls, and verifies that only the latest AJAX callback actually gets executed.

Why?

For cases in which you need to combine both 'debounce' & 'ajax'.
For example: If a certain user action triggers an AJAX call (heavy action), which in turn updates the DOM with the result. If you want the AJAX call to fire only after a [configurable-delay] milliseconds of "non-active" threshold, and then again, once an AJAX call returns, you want to make sure you update the DOM only for the latest call, a thing that can get tricky due to the nature of AJAX (remember what the first 'A' in AJAX stands for?).
Well, that's what ajaxDebounce.js is for!!!!

How?

Basically it is a wrapper for jQuery.ajax which provides the "debounce" functionality, and calls the AJAX callbacks only when needed- if it's the latest call that was triggered, while dropping callbacks for AJAX calls that are "no longer the latest".

Usage example:

          
  var $input = $('#my-input');
  
  // A dynamic function that constucts the relevant data for the AJAX call.
  var getAjaxObject = function(){ 
    return {
      url: '/do/something/cool/with/it',
      data: {value: $input.val()},
      success: function(data){
        // do whatever with 'data', it's promised to be only the latest call 
        // that was triggered only after the delay of 'non-active' threshold.
      },
      error: function(xhr, status, error){}
    };
  }
  $input.keyup(function(){$.ajaxDebounce({delay: 100, ajax: getAjaxObject()});});
  ------------------------^^^^^^^^^^^^^^^-------------------^^^^^^^^^^^^^^^------------
  -----------------------magic-happens-here--------------------and-here----------------

  $.ajaxDebounce({
    delay: 100,
    ajax: getAjaxOptions(),
    event: '',
    element: null
  })