window.scroll 事件监听是实时触发的,也就说每隔 16.7ms 就触发一次,单位时间内事件触发的次数过多,会影响系统性能。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>throttle</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <style>
        #long {
            height: 10000px;
            background-color: #666666;
        }
    </style>
</head>
<body>
<div id="long"></div>

<script>
    // 节水阀
    function throttle(func, delta, mustRun) {
        var timeoutID;
        var startTime = new Date();

        // 到这里只执行一次

        return function () {
            // 每次scroll都调

            var curTime = new Date();
            clearTimeout(timeoutID);

            if (curTime - startTime >= mustRun) {
                func.apply(this);
                startTime = curTime;
            } else {
                timeoutID = setTimeout(func, delta);
            }
        }
    }

    window.addEventListener("scroll", throttle(function () {
        console.log('do sth.');
    }, 200, 300));
</script>
</body>
</html>

参考: https://mp.weixin.qq.com/s/AS4KKqclDEpRha3VBPrFJw