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

什么是防抖和节流,他们的应用场景有哪些? #2

Open
leviscar opened this issue Jul 22, 2020 · 0 comments
Open

什么是防抖和节流,他们的应用场景有哪些? #2

leviscar opened this issue Jul 22, 2020 · 0 comments

Comments

@leviscar
Copy link
Owner

leviscar commented Jul 22, 2020

防抖

防抖,顾名思义,防止抖动,以免把一次事件误认为多次,敲键盘就是一个每天都会接触到的防抖操作。

防抖的使用场景

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

重点概念

防抖重在清零 clearTimeout(timer)

写法

es6写法

function debounce (f, wait) {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      f(...args)
    }, wait)
  }
}

es5写法

function myDebounce(listener, delay, handler) {
        var timer = null;
        return function () {
            var ctx = handler || this;
            var args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                listener.apply(ctx, args);
            }, delay);
        };
    }
exports. myDebounce =  myDebounce;

节流

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant