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

防抖和节流是什么,它们之间有什么区别,如何实现? #30

Open
CodeRookie262 opened this issue Jan 26, 2021 · 1 comment

Comments

@CodeRookie262
Copy link
Owner

No description provided.

@CodeRookie262
Copy link
Owner Author

防抖

防抖是在一段时间内多处触发时只调用开始或者最后一次,如果在这段时间内再次调用则重新计算周期。(可以想成玩王者荣耀回城功能一样,回城过程中需要等到一定的时间,如果被打倒或者操作了控制板时就在再次点击回城)

function debounce(callback, delay, immediate) {
        var timer = null;

        return function () {
          var that = this;

          if (timer) {
            clearTimeout(timer);
          }

          immediate && !timer && callback.apply(that, [].slice.call(arguments));
          
          timer = setTimeout(function () {
            immediate || callback.apply(that, [].slice.call(arguments));
            timer = null;
            clearTimeout(timer);
          }, delay);
        };
      }

节流

节流是在一定时间内多次触发只会调用一次。

function throttle(callback, delay) {
        var timer;

        return function () {
          var that = this;
          if (timer) {
            return false;
          }
          timer = setTimeout(function () {
            callback.apply(that, [].slice.call(arguments));
            timer = null;
            clearTimeout(timer);
          }, delay);
        };
      }

区别&场景

防抖适合在连续触发下只调用一次的场景,例如我们的搜索数据,窗口 resize等等;

节流适合在每个一定的间隔时间就触发一次的场景,例如我们的窗口滚动,按钮点击等等。

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