你可以包裝你的函數來檢查和跟蹤最後的執行。
我做了這樣的事情在最近的應用程序:
function createBuffer(_fn, _delay){
if (typeof _fn != 'function') return null;
if (isNaN(_delay)) _delay = 1000;
var lastCall = 0;
var wrappedFn = function(){
if (lastCall + _delay > Date.now()) return;
lastCall = Date.now();
_fn.apply(this, arguments);
};
wrappedFn.reset = function(){
lastCall = 0;
};
return wrappedFn;
}
這裏如何使用它
// give to the 'createBuffer' your function and a timeout value
var myBuffFn = createBuffer(function(){
// this code will be fired once every 5 seconds
}, 5000);
// to reset the timer (if you need to re-execute before the timeout ends)
myBuffFn.reset();
// now you can use your 'myBuffFn' as a normal function
myBuffFn();
// example inside an interval
setInterval(myBuffFn, 0);
對於您的情況:
var buffZoomed = createBuffer(zoomed, 5000);
現在只需撥打buffZoomed();
在那裏你需要和buffZoomed.reset();
你想重置超時時間