# 3.1.防抖

tip

触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间

简单例子如下:

// fn是用户传入需要防抖的函数
// time是等待时间
methods: {
  debounce (fn, time) {
        let timeout = null
        return function () {
          if (timeout !== null) clearTimeout(timeout)
          timeout = setTimeout(function () {
            fn('防抖')
          }, time)
        }
      }
  // 滚动停止后打印信息
  handle (params) {
    console.log('----------' + params)
  }
}
created () {
  let that = this;
  // 闭包方式优化滚动事件---滚动完成再触发事件
   window.addEventListener('scroll', that.debounce(that.handle, 500))
 }
// 不难看出如果用户调用该函数的间隔小于time的情况下,上一次的时间还未到就被清除了,并不会执行函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 3.1.1.防抖优化搜索框

一、在angular1.x项目优化搜索框

TIP

(1).通过方法形式触发搜索的,可以引入loadsh的debounce优化

步骤一:在index.html页面引入插件

<script src="https://cdn.bootcss.com/lodash.js/4.17.11/lodash.js"></script>
1

步骤二:作用的页面

<input type="text" data-ng-keyup="queryMethod()">
1

步骤三:在作用页面的controller里面添加防抖函数即可,如下所示



 



$scope.init = function () {
        // 添加loadsh的防抖动函数
        $scope.queryMethod = _.debounce($scope.queryMethod, 500);
    };
 $scope.queryMethod = function () {...}
1
2
3
4
5

TIP

(2).通过监听searchValue值搜索的,可以直接使用ng-model-options="{debounce: 400}"进行优化

步骤一:作用的页面

<input type="text" data-ng-model="searchValue" ng-model-options="{debounce: 400}">
1

步骤二:作用页面的controller

$scope.$watch('searchValue', function(newVal, oldVal) {
            $scope.searchMethod();
        });
1
2
3

# 3.2.节流

tip

对于连续执行某个函数时,控制每隔一段时间执行一次

简单例子如下:

methods: {
  // 抖动和节流
  throttling (fn, time, maxTimeLong) {
    let timeout = null
    let startTime = Date.parse(new Date())
    return function () {
      if (timeout !== null) clearTimeout(timeout)
      let currentTime = Date.parse(new Date())
      if (currentTime - startTime >= maxTimeLong) {
        fn('节流')
        startTime = currentTime
      } else {
        timeout = setTimeout(function () {
          fn('防抖')
        }, time)
      }
    }
  }
  // 滚动停止后打印信息
  handle (params) {
    console.log('----------' + params)
  }
}
created () {
    let that = this;
    // 节流+防抖动优化滚动事件
    window.addEventListener('scroll', that.throttling(that.handle, 500, 1000))
 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28