8

I'm sending a jquery $.post request on any checkbox change in a form. What I want is to delay the $.post for 500 ms in case a user checks more than one checkbox rapidly, to avoid multiple useless requests.

Here's my code, I've added a setTimeout function that seems to work with everything except this $.post function...

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

$(document).ready(function() {  

    $('.checkbox').change(function() {

        delay(function(){                             
            $.post("/?page_id=4", $("#selectors").serialize(), function(data){
                $('#results').html(data);
            }); 
        });

    }, 1000 );

});

Any idea why this doesn't work?

Phil
  • 83
  • 1
  • 3
  • I usually use setTimeout like that: `timer = window.setTimeout(function, 1000);` – ipalaus Mar 04 '11 at 14:30
  • 2
    Isn't the "}, 1000" at the wrong place? Shouldn't it be the second argument of the delay() function instead of the change() function? – Elian Ebbing Mar 04 '11 at 14:32
  • 1
    @ElianEbbing @Phil what Elian says. Your passing `1000` to `.change`. Also default `timer` to `undefined` or you'll accidentally kill the `setTimeout` with `id === 0` – Raynos Mar 04 '11 at 14:34
  • @ElianEbbing you're absolutely right, I missed that one, thanks for pointing it out! – Phil Mar 04 '11 at 14:43

2 Answers2

12

Live example

this:

$('.checkbox').change(function() {

    delay(function(){                             
        $.post("/?page_id=4", $("#selectors").serialize(), function(data){
            $('#results').html(data);
        }); 
    });

}, 1000 );

should be:

    $('.checkbox').change(function() {

        delay(function(){    
            alert('post');            
            $.post("/?page_id=4", $("#selectors").serialize(), function(data){
                $('#results').html(data);
            }); 
        }, 1000);

    });
subhaze
  • 8,815
  • 2
  • 30
  • 33
5

jQuery already has a delay function:

$(window).delay(500).queue(function() {
  $.post({});
});
sod
  • 3,804
  • 5
  • 22
  • 28
  • Update: I've added $.dequeue() and it runs as many times as you press the checkbox, just with intervals, so it beats the purpose. – raveren May 03 '12 at 16:27