4

I am using jQuery 1.8.

I have a series of checkboxes that a user can check to get information on particular product. When the box is check, a function is called and loads the product info into a div. CURRENTLY, the function fires immediately after each click. So, if the visitor checks all five boxes, the ajax call will be made five times.

What I want is for the function to fire after a certain period of time once the visitor stops clicking. The function should fire only once. The purpose of the delay is to limit the number of calls and create a smoother user experience.

Here is my HTML:

<input type='checkbox' class='SomeClass' data=prodid='1'> 1 
<input type='checkbox' class='SomeClass' data=prodid='2'> 2
<input type='checkbox' class='SomeClass' data=prodid='3'> 3
<input type='checkbox' class='SomeClass' data=prodid='4'> 4
<input type='checkbox' class='SomeClass' data=prodid='5'> 5
<div id='ProductInfoDiv'></div>

Here is my pseudo JavaScript:

// set vars
$Checkbox = $('input.SomeClass');
$ProductInfoDiv = $('div#ProductInfoDiv');

// listen for click
$Checkbox.click(getProductInfo);

// check which boxes are checked and load product info div
getProductInfo = function() {

    // create list of product id from boxes that are checked
    var QString = $Checkbox.filter(":checked");

    // LOAD THE PRODUCT DIV
    $ProductInfoDiv.load('SomePage.cfm?'+QString);

}

So, where do I put the delay? How do ensure that the function only fires ONCE?

Evik James
  • 10,335
  • 18
  • 71
  • 122
  • 1
    Same problem: http://stackoverflow.com/questions/2410937/delaying-actions-between-keypress-in-jquery. What you are looking for is often referred to as *debouncing*. jQuery plugin: http://benalman.com/projects/jquery-throttle-debounce-plugin/ (might be outdated though). – Felix Kling Nov 20 '12 at 19:44

6 Answers6

8

setTimeout with clearTimeout will accomplish this. Each click would do

var timeout = null;

$(element).click(function(){
    if(timeout)
    {
        clearTimeout(timeout);
    }

    timeout = setTimeout([some code to call AJAX], 500);
})

On each click, if there is a timeout it is cleared and restarted at 500 milliseconds. That way, the ajax can never fire until the user has stopped clicking for 500 milliseconds.

Scott S
  • 2,696
  • 16
  • 20
3
// set vars
$Checkbox = $('input.SomeClass');
$ProductInfoDiv = $('div#ProductInfoDiv');

// listen for click
$Checkbox.click(getProductInfo);
var timeout;
var timeoutDone = function () {
    $ProductInfoDiv.load('SomePage.cfm?'+QString);
}
// check which boxes are checked and load product info div
getProductInfo = function() {

    // create list of product id from boxes that are checked
    var QString = $Checkbox.filter(":checked");

    // LOAD THE PRODUCT DIV
    clearTimeout(timeout);
    timeout = setTimeout(timeoutDone, 4000);

}
Max
  • 8,671
  • 4
  • 33
  • 46
3
var clickTimer = false;

// listen for click
$Checkbox.click(function(){
   if(clickTimer) { 
      // abort previous request if 800ms have not passed
      clearTimeout(clickTimer);
   }

   clickTimer = setTimeout(function() {
       getProductInfo();
   },800); // wait 800ms
});

Working example here: http://jsfiddle.net/Th9sb/

lostsource
  • 21,070
  • 8
  • 66
  • 88
  • This won't solve the issue. It will still call getProductInfo after 200ms after every checkbox – Max Nov 20 '12 at 19:39
  • 1
    I think you want to pull the `if(clickTimer)` check out of the setTimeout callback. It will always be true in your case, because it only gets fired in the setTimeout callback, which means `clickTimer` must be set. – Matt Nov 20 '12 at 19:44
  • Imagine you have the click events, A, B, C. If all of them happen very quickly, A's timeout callback will cancels C's timeout, but B will still be executed. Or B is canceled and C is executed... not an optimal solution. The current event handler should cancel past timeouts, not vice versa. – Felix Kling Nov 20 '12 at 19:46
1

Would it be possible to disable the checkboxes until the ajax request has been completed?

$('.SomeClass').on('click', function(e) {
    $('.SomeClass').attr('disabled', true);

    //-- ajax request that enables checkboxes on success/error
    $.ajax({
        url: "http://www.yoururl.com/",
        success: function (data) {
            $('.SomeClass').removeAttr('disabled');
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $('.SomeClass').removeAttr('disabled');
        }
    });
});
Don Boots
  • 2,028
  • 2
  • 18
  • 26
  • Yes, that would be possible and might be a good idea in some cases. In this case, it's not a good idea at all. Odds are, the user will WANT multiple boxes checked. And the boxes are very close to each other. I appreciate the idea though. – Evik James Nov 20 '12 at 19:59
0

i think you have to put it here

$Checkbox.click(getProductInfo);

it should be like this : working example is here--> http://jsbin.com/umojib/1/edit

$Checkbox.one("click", function() {
  setTimeout(function() {
   getProductInfo();
  },200);
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0

If you are allowed to add another library.

Underscore has a debounce function which fits perfect on what you want.

function callback(){
    // some code to call AJAX
}

$(element).click(_.debounce(callback, 500))

```