以下は、リクエストを調整するために私が書いたコードです。
初期化:
var global = {};
global.searchThrottle = Object.create(requestThrottle);
使用法:
this.searchThrottle.add(function(){
//Do some search or whatever you want to throttle
});
ソースコード:
// 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()ソースコード(「Javascript:TheGoodParts」から取得):
if( typeof Object.create !== 'function'){
Object.create = function(o){
var F = function(){};
F.prototype = o;
return new F();
};
}