码迷,mamicode.com
首页 > 其他好文 > 详细

防抖和节流

时间:2018-08-28 11:27:23      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:操作   console   0ms   run   timeout   cti   art   class   tor   

防抖:一定时间内频繁触发一个事件则不会执行对应的操作,只有大于这个时间再次触发才会执行 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);
};

 

防抖和节流

标签:操作   console   0ms   run   timeout   cti   art   class   tor   

原文地址:https://www.cnblogs.com/jiujiaoyangkang/p/9546721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!