Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding delay to a $.post jquery request

Tags:

jquery

post

delay

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?

like image 622
Phil Avatar asked Mar 04 '11 14:03

Phil


2 Answers

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

    });
like image 137
subhaze Avatar answered Nov 20 '22 22:11

subhaze


jQuery already has a delay function:

$(window).delay(500).queue(function() {
  $.post({});
});
like image 5
sod Avatar answered Nov 20 '22 22:11

sod