首页 > 其他 > 详细

节流和去抖

时间:2019-09-02 14:50:55      阅读:75      评论:0      收藏:0      [点我收藏+]

两者都是控制事件响应的频繁触发。

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

<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>

技术分享图片

防抖(debounce):指触发事件后在n秒内函数只执行一次,如果在n秒内又触发了事件,则会重新计算这次函数的执行时间。

在以下例子中,如果在n秒内又触发了事件,就清除当前的定时器,从新计时,从现在开始到n秒后在执行该函数,下图为效果图:

    let num = 1;
    let content = document.getElementById(‘content‘);

    function count() {
        content.innerHTML = num++;
    };
    content.onmousemove = debounce(count, 1000);

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

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

技术分享图片

节流(throttle):连续触发事件但是在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;
        }
    }
}
// 定时器版

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

    }
}

 

 

原文:https://www.jianshu.com/p/c8b86b09daf0

节流和去抖

原文:https://www.cnblogs.com/xjy20170907/p/11445621.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!