25. js - interview - throttling

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 500px;
            height: 500px;
            background: #ccc;
            font-size: 100px;
        }
    </style>
</head>

<body>

    <div class="box"></div>

</body>

</html>
<script src="./lodash.min.js"></script>
<script>

    // 节流:单位时间内,频繁地触发事件,只执行一次
    // 使用场景:高频事件:鼠标移动mousemove、页面尺寸缩放resize、滚动条滚动scroll等等

    const box = document.querySelector('div');
    let i = 0;

    function myFn() {
        i++;
        this.innerHTML = i;
    }

    // 方案一:使用lodash库的_.throttle()方法,_.throttle()方法会返回一个函数
    // box.addEventListener('mousemove', _.throttle(myFn, 1000));

    // 方案二:自己手写节流函数
    box.addEventListener('mousemove', throttle(myFn, 1000));

    function throttle(fn, time) {
        let timer = null;
        return function () {
            if (!timer) {
                timer = setTimeout(() => {
                    fn.call(this);
                    timer = null;
                }, time);
            }
        }
    }


</script>

Guess you like

Origin blog.csdn.net/EchoLiner/article/details/131082653