Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create delay before ajax call?

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?

like image 782
Evik James Avatar asked Dec 06 '22 10:12

Evik James


1 Answers

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.

like image 114
Scott S Avatar answered Dec 11 '22 11:12

Scott S