2017-02-15 17 views
1

我有一个称为zoomed的函数,可以在用户放大屏幕的任何时候执行。因此,用户可以在几秒钟内执行几次缩放操作。上一次调用函数时,我想记录'完成缩放'。达到此目的的最佳方法是什么?只有在过去5秒内调用了一次函数,我该如何执行某些操作?

function zoomed() { 
    console.log('called'); 
    // If this has only been called once in past 
    // 5 seconds, user is done zooming 
    // console.log('done zooming') 
} 

回答

3

像这样的工作:

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"); 
} 

Here是该代码使用的一个例子。留意控制台。


zoomComplete()函数充当回调,当用户完成缩放时会触发回调。

如果这不是必要的,你可能会在这里消除一些功能 - 我打破了它的可读性。在同一笔记中,如果您想要整合但又是个人偏好,只需将resetZoomTimer()中的功能移动到zoomed()函数中即可。

0

你可以包装你的函数来检查和跟踪最后的执行。

我做了这样的事情在最近的应用程序:

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();你想重置超时时间

0

我个人有一个全局变量(可由函数的所有实例访问),它在函数执行结束时分配了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); 
}; 
1

你在寻找什么是通常被称为防抖动。它在您的场景中经常使用。

自己编写函数并不难,但像lodash这样的实用程序库有很好的实现。

widget.on('zoom', _.debounce(zoomed, 5000, { trailing: true })); 

这样做是开始缩放时发生,那么在放大5秒暂停后,调用zoomed()功能收听。

请参阅https://lodash.com/docs/4.17.4#debounce

相关问题