Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

防抖、节流(javascript) #9

Open
YoursJoker opened this issue Aug 6, 2020 · 0 comments
Open

防抖、节流(javascript) #9

YoursJoker opened this issue Aug 6, 2020 · 0 comments

Comments

@YoursJoker
Copy link
Owner

YoursJoker commented Aug 6, 2020

javascript系列之 防抖 (debounce)与节流 (throttle) 篇

频繁的事件触发,会消耗很多的资源,甚至出现卡顿现象。解决这个问题一般有防抖(debounce)和节流(throttle)两个方案

1.防抖 (debounce)

原理:

只以最后一次触发的时间为准,延迟n秒后才执行。如果延迟n秒的时间内又触发事件,则以新的事件为时间基准,延迟n秒再执行

应用场景:

  1. 登录、发短信等按钮避免用户点击太快,以致于发送了多次请求,需要防抖
  2. 调整浏览器窗口大小时,resize 次数过于频繁,造成计算过多,此时需要一次到位,就用到了防抖
  3. 文本编辑器实时保存,当无任何更改操作一秒后进行保存

简单代码:防抖重在清零 clearTimeout(timer)

function debounce(func, wait) {
    var timeout;

    return function () {
        clearTimeout(timeout)
        timeout = setTimeout(func, wait);
    }
}

2.节流 (throttle)

原理:

控制事件发生的频率,如控制为1s发生一次,甚至1分钟发生一次

应用场景:

  1. scroll 事件,每隔一秒计算一次位置信息等
  2. 浏览器播放事件,每个一秒计算一次进度信息等
  3. input 框实时搜索并发送请求展示下拉列表,每隔一秒发送一次请求 (也可做防抖)

简单代码:节流重在开锁关锁 timer = setTimeout timer = nullnowTime - lastTime > wait

//1.设置定时器
function throttle(func, wait) {
    var timeout = null;

    return function() {
        if (!timeout) {
            timeout = setTimeout(function(){
                timeout = null;
                func()
            }, wait)
        }
    }
}

//2.使用时间戳
function throttle2 (func, wait) {
    let lastTime = 0;

    return function () {
        let nowTime = +new Date();
        if (nowTime - lastTime > wait) {
            func();
            lastTime = nowTime
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant