如何中止$ .post请求

i have this event on keydown:

$.post("search.php", { s: $('#box_s').val()},
               function(data) {
                  /**/
               }
});

the problem is that as many keydown as many requests and sometimes older requests override recent requests results

so i would need to

$('input#box_s').keydown(function(){
     abort_previous_post();
     $.post("search.php", { s: $('#box_s').val()},
                   function(data) {
                      /**/
                   }
    });
});

is that posible?

I'd approach it something like this:

var requestCount = 0;

$('input#box_s').keydown(function(){
     requestCount++;
     var thisRequestCount = requestCount;
     $.post("search.php", { ingredientes_s: $('#box_s').val()},
                   function(data) {
                      if(thisRequestCount!=requestCount) return;
                      /**/
                   }
    });
});

You can throttle it so that a request is not made until the user has stopped typing for x milliseconds. 250-400ms seems a good value:

function throttle( fn, time ) {
    var timer = 0;

    return function() {
        window.clearTimeout( timer );
        var self = this,
            args = [].slice.call( arguments );


        timer = setTimeout( function() {
            return fn.apply( self, args );
        }, time );
    };

}

And usage:

$('input#box_s').keydown( throttle( function(){

     $.post("search.php", { s: $('#box_s').val()},
                   function(data) {
                      /**/
                   }
    });
}, 400 ) );

In this case a request is made after the user starts typing and then stops for 400ms.

What you want to do is not start the request unless there has been a slight delay:

var timeoutID;
$('#box_s').keydown(function () {
    clearTimeout(timeoutID);
    timeoutID = setTimeout(function () {
        $.post("search.php", { ingredientes_s: $('#box_s').val()}, function(data) {
            /** **/
        });
     }, 500);
});

Check this jsFiddle for a demo.

The post call is just a convince method for the Ajax handler, so capture the xhr, and abort it.

var jqxhr;

$('input#box_s').keydown(function(){
     if (jqxhr) jqxhr.abort();
     $.post("search.php", { ingredientes_s: $('#box_s').val()},
                   function(data) {
                      /**/
                   }
    });
});