问题
Does jQuery have any tools I can use for request-throttling? Something similar to how auto complete works.
More specifically this is the kind of thing I'm trying to do:
**Customer entry:** First Name: J Last Name: Smi **Search results:** Joe Shmoe -edit button- John Smith -edit button- Jane Smith -edit button- Joe Smithers -edit button-
When a user types a anything in either of the boxes, I'd like to formulate the request myself, and then jQuery can decide when and if to send the request, and then I would provide the code for handling the response.
回答1:
Below is the code I ended up writing for throttling requests.
Initialization:
var global = {};
global.searchThrottle = Object.create(requestThrottle);
Usage:
this.searchThrottle.add(function(){
//Do some search or whatever you want to throttle
});
Source code:
// runs only the most recent function added in the last 400 milliseconds, others are
// discarded
var requestThrottle = {};
// Data
requestThrottle.delay = 400; // delay in miliseconds
requestThrottle.add = function(newRequest){
this.nextRequest = newRequest;
if( !this.pending ){
this.pending = true;
var that = this;
setTimeout( function(){that.doRequest();}, this.delay);
}
}
requestThrottle.doRequest = function(){
var toDoRequest = this.nextRequest;
this.nextRequest = null;
this.pending = false;
toDoRequest();
}
Object.create() source code (taken from "Javascript: The Good Parts"):
if( typeof Object.create !== 'function'){
Object.create = function(o){
var F = function(){};
F.prototype = o;
return new F();
};
}
来源:https://stackoverflow.com/questions/3963299/jquery-auto-complete-request-throttling