javascript --- > 防抖与节流

先做一个监听鼠标移动的base:

<style>
    #content{
        height:150px;
        width:200px;
        text-align:center;
        color:#fff;
        background-color:#ccc;
        font-size: 70px;
    }
</style>
<div id="content"></div>
<script>
    let content = document.getElementById('content');
    let num = 0;
    function count () {
        content.innerHTML = num++
    };
    content.onmousemove = count;
</script> 

在这里插入图片描述

// 鼠标在灰色方块内移动时,数字会疯狂的涨.

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

// 非立即执行: 本例中是指,鼠标移动,然后再某个地方停留s秒后,才执行函数
function debounce(func, wait) {
    let timeout;
    return function () {
        let self = this;
        let args = arguments;
         
        if (timeout ) clearTimeout(timeout);
         
        timeout = setTimeout( () => {
            func.apply(self, args);
        }, wait);
    }
}
content.onmousemove = debounce( count, 1*1000);

// 立即执行: 立即执行,然后等待s秒(中途若移动则重新计算)后,然后立即执行,再等待s秒
function debounce(func, wait) {
    let timeout;
    return function () {
        let self = this;
        let args = arguments;
         
        if ( timeout ) clearTimeout( timeout ) ;
         
        let callNow = !timeout;
        timeout  = setTimeout( () => {
            timeout = null;
        }, wait)
        if ( callNow ) func.apply(self, args);
    }
}

// 混合防抖(immediate为真代表立即执行)
function debounce(func, wait, immediate=false) {
    let timeout;
     
    return function () {
        let self = this;
        let args = arguments;
         
        if( timeout ) clearTimeout( timeout );
        if( immediate) {  // 立即执行
            let callNow = !timeout;
            timeout = setTimeout ( () => {
                timeout = null;
            }, wait)
            if ( callNow ) func.apply(self, args);
        } else {
            timeout = setTimeout( () => {
                fn.apply(self, args);
            }, wait);
        }
    }
}

节流(throttle): 所谓节流,就是指连续触发事件,但是在n秒内该事件只处理一次

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

参考 函数防抖和节流

猜你喜欢

转载自blog.csdn.net/piano9425/article/details/93649507