你可以包装你的函数来检查和跟踪最后的执行。
我做了这样的事情在最近的应用程序:
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();
你想重置超时时间