[英]How can I execute something only if the function has been called once in the past 5 seconds?
我有一个名为zoomed
的函数,该函数在用户放大屏幕的任何部分时执行。 因此,随着用户缩放,它可以在几秒钟内执行几次。 我想在上次调用该函数时记录“完成缩放”。 实现此目标的最佳方法是什么?
function zoomed() {
console.log('called');
// If this has only been called once in past
// 5 seconds, user is done zooming
// console.log('done zooming')
}
这样的事情会起作用:
var doneZooming = true; //Global variable to store the current "state" of zooming
var zoomTimeout = null; //Variable to store our 5-second timer
function zoomed() {
resetZoomTimer();
console.log("zooming");
}
function resetZoomTimer() {
doneZooming = false;
clearTimeout(zoomTimeout); //End current timer
zoomTimeout = setTimeout(zoomComplete, 5000); //Reset the timer to 5 seconds
}
function zoomComplete() {
doneZooming = true;
console.log("zooming complete");
}
这是此代码使用中的示例。 留意控制台。
zoomComplete()
函数充当一个回调,将在用户完成缩放后触发。
如果没有必要,您可以在此处消除一些功能-为了便于阅读,我将其分开。 同样,如果您希望合并个人喜好,则可以将resetZoomTimer()
的函数简单地移到zoomed()
函数中。
您要寻找的通常称为反跳 。 在像您这样的场景中定期使用它。
自己编写函数并不难,但是lodash之类的实用程序库具有良好的实现。
widget.on('zoom', _.debounce(zoomed, 5000, { trailing: true }));
这样做是在发生缩放时开始监听,然后在暂停5秒后调用zoomed()
函数。
我个人将拥有一个全局变量(该函数的所有实例均可访问),该变量在函数执行结束时分配了setTimeout函数。 这将创建一个仅在该函数的另一个实例未清除的情况下才会执行的计时器。
例如
var zoomTimer;
function zoomed() {
console.log('called');
// Clears the timeout associated with the variable
clearTimeout(zoomTimer);
// Sets the 5 second timeout
zoomTimer = setTimeout(function() { console.log('done zooming'); }, 5000);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.