最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create delay before ajax call? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Nov 20, 2012 at 19:33 Evik JamesEvik James 10.5k19 gold badges75 silver badges123 bronze badges 1
  • 1 Same problem: stackoverflow.com/questions/2410937/…. What you are looking for is often referred to as debouncing. jQuery plugin: benalman.com/projects/jquery-throttle-debounce-plugin (might be outdated though). – Felix Kling Commented Nov 20, 2012 at 19:44
Add a comment  | 

6 Answers 6

Reset to default 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.

// 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);

}
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/

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');
        }
    });
});

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);
});

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))

```

发布评论

评论列表(0)

  1. 暂无评论