js 节流 防抖 代码实现和原理


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
//防抖
    function debounce(fn, wait) {
        var timeout = null;
        return function () {
            if (timeout !== null)
                clearTimeout(timeout);
            timeout = setTimeout(fn, wait);
        }
    }
    // 处理函数
    function handle() {
        console.log(Math.random());
    }
    // 滚动事件
    window.addEventListener('scroll', debounce(handle, 1000));
</script>
<script>
//节流
    var throttle = function (func, delay) {
        var prev = Date.now();
        return function () {
            var context = this;
            var args = arguments;
            var now = Date.now();
            if (now - prev >= delay) {
                func.apply(context, args);
                prev = Date.now();
            }
        }
    }

    function handle() {
        console.log(Math.random());
    }
    window.addEventListener('scroll', throttle(handle, 1000));
</script>

</html>

防抖就是防止事件频繁触发,针对最后一次触发才执行函数

节流就是只在单位的时间内才触发该事件

防抖 节流 的好处就是防止过分的触发事件执行函数,导致浏览器性能降低或者体验不好


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM