不使用 3rd 方库,只需使用 Date.getTime() 并将其存储为一些变量:
var lastRun = null;
function oneIn2Min() {
if (lastRun == null || new Date().getTime() - lastRun > 2000) {
console.log('executed');
}
lastRun = new Date().getTime();
}
oneIn2Min(); // prints 'executed'
oneIn2Min(); // does nothing
oneIn2Min(); // does nothing
setTimeout(oneIn2Min, 2500); // prints 'executed'
您还可以选择从中制作一些简单的对象(以使您的代码井井有条)。它可能看起来像这样:
var CachedCall = function (minTime, cbk) {
this.cbk = cbk;
this.minTime = minTime;
};
CachedCall.prototype = {
lastRun: null,
invoke: function () {
if (this.lastRun == null || new Date().getTime() - this.lastRun > this.minTime) {
this.cbk();
}
this.lastRun = new Date().getTime();
}
};
// CachedCall which will invoke function if last invocation
// was at least 2000 msec ago
var c = new CachedCall(2000, function () {
console.log('executed');
});
c.invoke(); // prints 'executed'
c.invoke(); // prints nothing
c.invoke(); // prints nothing
setTimeout(function () {c.invoke();}, 2300); // prints 'executed'