节流与防抖

节流与防抖,第1张

防抖:在频繁触发事件时,事件只执行一次,并且是最后一次触发的时候

主要思想:给需要触发业务代码加上一个定时器,并且如果在定时器设定的时间内,该业务代码再次被触发,则清除上一次的定时器。

节流:在频繁触发事件时,事件在一定时间间隔内,只执行一次

主要思想:控制执行次数,同样,设置一个定时器,设置间隔时间,设定一个触发业务代码的全局状态,为true时触发事件,只有在执行完定时器中的业务代码时,状态才为true,否则不触发业务代码。

滚动条事件触发案例

当拖动页面滚动条时,触发我们所需要的业务代码,频繁地拖拽导致1秒内事件触发了93次,如果业务代码增多,会导致页面卡顿;如果向后端发ajax,会导致后台服务器压力过大、崩溃等等问题。

html

<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>Documenttitle>
    <style>
        body {
            height: 2000px
        }
        div {
            height: 200px;
            width: 200px;
            overflow: scroll;
            margin: auto;
            background-color: #333;
        }
    style>
head>
<body>
    <div id="box">
        <div style="height: 300px">div>
    div>
body>

js

var box = document.getElementById('box')
    box.onscroll = function() {
        console.log(123)
    }
解决办法:

1、防抖

var box = document.getElementById('box')
box.onscroll = debounce(sayhello, 500)
    function sayhello() {
        console.log(this)
        console.log('hello world')
    }

    // 防抖函数
    function debounce(fn, delay) {
        let timer
        return function() {
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                // 改变this指向
                fn.call(this)
            }, delay)
        }
    }
</script>

2、节流

var box = document.getElementById('box')
box.onscroll = throttle(sayhello, 500)
    // 节流函数
    function throttle(fn, delay) {
        let flag = true
        return function() {
            if (flag) {
                setTimeout(() => {
                    flag = true
                    // 业务代码
                    // 改变this指向
                    // fn.apply(this)
                    fn.call(this)
                }, delay)
            }
            flag = false
        }
    }
    function sayhello() {
        console.log(this)
        console.log('hello world')
    }
</script>
两者封装:采用闭包,

原因:1.需要设置一个全局的变量存放定时器;2.防抖功能代码和业务代码混合在一起,一旦业务代码量增多不易于维护。
两者应用场景:搜索框输入查询,按钮提交事件,浏览器的窗口缩放,浏览器滚动条事件触发

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/2990025.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存