防抖和节流

防抖:一定时间内频繁触发一个事件则不会执行对应的操作,只有大于这个时间再次触发才会执行 action

function _debounce(func, wait) {
    // 一上来就执行了,this 是 window
    let timer = null;
    let context, args;
    return function () {
        // 返回的函数 this 才是 oBox
        context = this;
        args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            func.apply(context, args);
        }, wait);
    }
}
let oBox = document.querySelector('#root');
oBox.onmousemove = _debounce(function () {
    console.log(1);
}, 500);

节流:一定时间间隔才执行对应的操作,无论你多么频繁的触发事件

// 函数节流
let canRun = true;
document.getElementById("root").onmousemove = function () {
    if (!canRun) {
        return;
    }

    // 马上设置 false,在 300ms 内触发事件会直接 return
    canRun = false;
    setTimeout(function () {
        console.log(2);
        // 300ms 后可以继续了
        canRun = true;
    }, 300);
};

 

posted @ 2018-08-28 10:48  DuangDang  阅读(110)  评论(0编辑  收藏  举报