有可用的一個非常好的方法上unscriptable.com:
Function.prototype.debounce = function (threshold, execAsap) {
var func = this, // reference to original function
timeout; // handle to setTimeout async task (detection period)
// return the new debounced function which executes the original function
// only once until the detection period expires
return function debounced() {
var obj = this, // reference to original context object
args = arguments; // arguments at execution time
// this is the detection function. it will be executed if/when the
// threshold expires
function delayed() {
// if we're executing at the end of the detection period
if (!execAsap)
func.apply(obj, args); // execute now
// clear timeout handle
timeout = null;
};
// stop any current detection period
if (timeout)
clearTimeout(timeout);
// otherwise, if we're not already waiting and we're executing at the
// beginning of the waiting period
else if (execAsap)
func.apply(obj, args); // execute now
// reset the waiting period
timeout = setTimeout(delayed, threshold || 100);
};
}
這將讓你做的事:
// call the function 200ms after the bounds_changed event last fired:
google.maps.event.addListener(map, 'bounds_changed', (function() {
// here goes an ajax call
}).debounce(200));
// call the function only once per 200ms:
google.maps.event.addListener(map, 'bounds_changed', (function() {
// here goes an ajax call
}).debounce(200,true));
如果你不希望其他人充實到Function.prototype
有一個獨立的function debounce(func, threshold, execAsap)
可在blog post獲得。
感謝所有爲你解答! – Florent2 2010-07-16 16:28:15