1. 程式人生 > >函數防抖,與函數節流

函數防抖,與函數節流

操作 ott mouse enter return 進行 判斷 scroll 執行時間

在項目中,我們會經常使用到mouseover,mouseenter,resize,scroll等,這些函數會頻繁的觸發,因此會造成資源浪費。

因此我們需要進行優化,這個時候就需要使用到函數防抖(debounce),或者函數節流(throttle)

1)函數防抖(debounce)

就是指觸發事件後在 n 秒內函數只能執行一次,如果在 n 秒內又觸發了事件,則會重新計算函數執行時間(簡言之:在我們操作結束之後的某一個時間之後執行一次

   var timer = null;
    function debounce () {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function (){
            console.log("debouce");
        },400);
    }

2)函數節流

就是指連續觸發事件但是在 n 秒中只執行一次函數(即使不停止操作,他也會一直按固定時間間隔執行

   var _timer = ‘‘;
    function thort () {
        if (_timer) {
            return ‘‘;
        }
        _timer = setTimeout(function () {
            console.log(‘thort‘);
            clearTimeout(_timer);
            _timer =‘‘;
        },1000);
    }
    // 或者
    var previous = 0;
    function thortNew () {
        var now = new Date();
        if (now - previous > 400) {
            console.log(‘thortNew‘);
            previous = now;
        }
    }

分析:他們的不同?

如果都是使用setTimeout去實現的前提下,他們的區別就在於判斷timer是否有值得情況下,是clearTimerout(timer)還是存粹的結束掉函數執行return。

參考鏈接:https://www.jianshu.com/p/c8b86b09daf0

函數防抖,與函數節流