函数节流与函数防抖

函数节流

1. 定义

一个函数在一定时间段内只执行一次

2. 方案

  • 时间戳

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // 时间戳方案
    function throttle(fn,wait){
    var pre = Date.now();
    return function(){
    var context = this;
    var args = arguments;
    var now = Date.now();
    if( now - pre >= wait){
    fn.apply(context,args);
    pre = Date.now();
    }
    }
    }

    function handle(s){
    console.log(s)
    }
    var test = throttle(handle, 1000)
    window.addEventListener("mousemove", test(1))
  • 定时器方案

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // 定时器方案
    function throttle(fn,wait){
    var timer = null;
    return function(){
    var context = this;
    var args = arguments;
    if(!timer){
    timer = setTimeout(function(){
    fn.apply(context,args);
    timer = null;
    },wait)
    }
    }
    }

    function handle(s){
    console.log(s)
    }
    var test = throttle(handle, 1000)
    window.addEventListener("mousemove", test(1))

3. 使用场景

  • 懒加载,滚动加载等
  • 搜索联想功能
  • 防止重复点击,表单重复提交,扫描二维码是否成功等

4. 总结

​ 说到底就是为了节约计算机资源,在合适的场景使用

函数防抖

1. 定义

​ 在一段操作中,每一段时间只执行一次,并且是在最后执行一次

2. 实现原理

​ 利用clearTimeout和setTimeOut实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var timer; // 维护同一个timer
function debounce(fn, delay) {
clearTimeout(timer);
timer = setTimeout(function(){
fn();
}, delay);
}
//优化后
function debounce(fn, delay) {
var timer; // 维护一个 timer
return function () {
var that = this; // 取debounce执行作用域的this
var args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
fn.apply(that, args); // 用apply指向调用debounce的对象,相当于that.fn(args);
}, delay);
};
}

3. 应用场景

  • 搜索框输入,只需检测用户最后一次输入完,再发送请求
  • 手机号、邮箱等验证
  • resize函数,只需窗口调整完成后,计算窗口大小,防止重复渲染