joken-前端工程师

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
<!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>

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

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

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

posted on 2020-05-30 19:36  joken1310  阅读(2176)  评论(0编辑  收藏  举报