# 防抖节流

  1. 常用于页面按钮频繁点击(防抖)
  2. 页面滚动(节流)

html部分


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>函数的防抖与节流</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            margin: 100px;
            line-height: 100px;
            text-align: center;
            color: #fff;
        }

        #box1 {
            background-color: #f00;
        }

        #box2 {
            background-color: #0f0;
        }
    </style>
</head>

<body>
    <div id="box1">防抖</div>
    <div id="box2">节流</div>
</body>

</html>
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
29
30
31
32
33
34
35

防抖

    //函数的防抖指在一定时间范围内只触发一次
    // 接受一个回调函数 fn
    // 一个时间间隔 time
    function debounce(fn, time) {
        let timer = null;
        return function () {
            clearTimeout(timer);
            timer = setTimeout(() => {
                console.log(this, '===this');
                fn.call(this, arguments)
            }, time);
        }
    }

    const clickOne = debounce(function () {
            console.log('函数防抖开始');
        }, 500);

        box1.onclick = clickOne;

    // box1.onclick = debounce(function () {
    //     console.log('函数防抖开始');
    // }, 500);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

节流





    // 函数节流
    //表示一定时间内肯定触发一次,可以缓解由于频繁触发带来的性能问题,但一定会触发更新
    function throttle(fun, time) {
        var startTime = new Date();
        var timeId = null;
        return function () {
            var currTime = new Date();
            clearTimeout(timeId);
            if (currTime - startTime >= time) {
                fun.call(this, arguments);
                startTime = new Date();
            } else {
                timeId = setTimeout(() => {
                    fun.call(this, arguments);
                    startTime = new Date();
                }, currTime - startTime)
            }

        }

    }

    var isThrottle = throttle(function () {
        console.log('函数节流');
    }, 2000)
    box2.onclick = isThrottle;
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
29
30
最后更新时间: 5/19/2023, 1:53:00 PM