美文网首页
函数防抖和节流

函数防抖和节流

作者: TouchMe丶 | 来源:发表于2019-03-20 10:25 被阅读0次

转自 简书

什么是函数防抖和节流

在前端开发过程中,我们经常会遇到需要绑定一些持续性出发事件的场景.例如resize,scroll,mousemove等等。绝大多数时候我们并不希望在事件持续触发的过程中name频繁地去执行函数。
通常这种情况下,我们会用到防抖和节流。
例如,我们经常会遇到如下情况

<div id="content" style="height:150px;line-height:150px;text-align:center; color: #fff;background-color:#ccc;font-size:80px;"></div>
<script>
    let num = 1;
    let content = document.getElementById('content');

    function count() {
        content.innerHTML = num++;
    };
    content.onmousemove = count;
</script>

在上述代码中,div绑定了mousemove事件,当鼠标在div(灰色)区域中移动的时候,就会持续性地触发事件,导致事件频繁执行count函数。效果如下:


image

大家可以看到,在没有通过其他操作的情况下,函数被频繁地执行了,导致页面上数据变化非常之快。所以,接下来我们来对这个函数进行优化。看看防抖和节流是如何处理这个问题的。

防抖(debounce)

所谓防抖,就是触发事件后在n秒内函数只能执行一次,如果n秒又触发了事件,则会重新计算函数时间。
防抖函数分为非立即执行版本和立即执行版本。

非立即执行版

function debounce(func, wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;//这两行看来是必要的

        if (timeout) clearTimeout(timeout);
        
        timeout = setTimeout(() => {
            func.apply(context, args)
        }, wait);
    }
}

非立即执行版的意思是出发时间后函数不会立即执行,而是在n秒后执行,如果在n秒内事件再次出发,则重新计算函数执行时间。
我们依旧用上面绑定mousemove事件的例子,通过上面的防抖函数,我们这一这么使用:

content.onmousemove = debounce(count,1000);

效果如下:


image

可以看到,在触发时间后1秒才执行,而如果我们在出发事件后的1秒内又触发了事件,则会重新计算函数执行时间。

上述防抖代函数的代码还需要注意的是this和参数的传递

let context = this;
let args = arguments;

防抖函数的代码使用这两行代码来获取this和参数,是为了让debounce函数最终返回的函数this指向不变以及依旧能接收到e参数。

立即执行版

function debounce(func,wait) {
    let timeout;
    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);

        let callNow = !timeout;
        timeout = setTimeout(() => {
            timeout = null;
        }, wait)

        if (callNow) func.apply(context, args)
    }
}

立即执行版的意思是触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果。
使用方法同上,效果如下:


image

双剑合壁版本

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
function debounce(func,wait,immediate) {
    let timeout;

    return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
            var callNow = !timeout;
            timeout = setTimeout(() => {
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
    }
}

节流

所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。
对于节流,一般有两种方式可以实现,分别是时间戳版和定时器版。

时间戳版:

function throttle(func, wait) {
    let previous = 0;
    return function() {
        let now = Date.now();
        let context = this;
        let args = arguments;
        if (now - previous > wait) {
            func.apply(context, args);
            previous = now;
        }
    }
}

使用方法如下:

content.onmousemove = throttle(count,1000);

效果如下:


image

可以看到,在持续触发事件的过程中,函数会立即执行,并且每 1s 执行一次。

定时器版

function throttle(func, wait) {
    let timeout;
    return function() {
        let context = this;
        let args = arguments;
        if (!timeout) {
            timeout = setTimeout(() => {
                timeout = null;
                func.apply(context, args)
            }, wait)
        }

    }
}

使用方式同上,效果如下


image

可以看到,在持续触发事件的过程中,函数不会立即执行,并且每 1s 执行一次,在停止触发事件后,函数还会再执行一次。
我们应该可以很容易的发现,其实时间戳版和定时器版的节流函数的区别就是,时间戳版的函数触发是在时间段内开始的时候,而定时器版的函数触发是在时间段内结束的时候。

同样地,我们也可以将时间戳版和定时器版的节流函数结合起来,实现双剑合璧版的节流函数。

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 */
function throttle(func, wait ,type) {
    if(type===1){
        let previous = 0;
    }else if(type===2){
        let timeout;
    }
    return function() {
        let context = this;
        let args = arguments;
        if(type===1){
            let now = Date.now();

            if (now - previous > wait) {
                func.apply(context, args);
                previous = now;
            }
        }else if(type===2){
            if (!timeout) {
                timeout = setTimeout(() => {
                    timeout = null;
                    func.apply(context, args)
                }, wait)
            }
        }
    }
}

相关文章

网友评论

      本文标题:函数防抖和节流

      本文链接:https://www.haomeiwen.com/subject/beoamqtx.html