Skip to content

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

Open

Description

@CodeRookie262
No description provided.

Activity

  1. CodeRookie262 commented on Jan 27, 2021

    @CodeRookie262
    OwnerAuthor

    防抖

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

    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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions