函数防抖,与函数节流

在项目中,我们会经常使用到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

原文地址:https://www.cnblogs.com/evaling/p/10454140.html