2017-02-15 47 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

相關問題