防抖和节流

<!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;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        // 什么是防抖
        // 在规定的时间n秒钟函数只执行一次,如果n秒内重复操作,函数时间会从新计算
        // 例如:5秒钟执行一次函数fn,第4秒的时候又操作页面那么时间从新计算5秒后在执行
        // debounce  防抖

        // 重绘和回流
        // 重绘:页面的颜色改变,结构不变
        // 回流:页面的结构(或者大小)发生变化
        // 定义一个防抖函数

        function debounce(fn, time) {
            let timer = null
            return function () {
                let that = this
                if (timer) {
                    clearTimeout(timer)
                }
                timer = setTimeout(() => {
                    fn.apply(that)
                }, time)
            }
        }

        var oBox = document.querySelector("#box")
        var num = 0
        // oBox.onmousemove = function () {
        //     num++
        //     oBox.innerHTML = num
        // }
        oBox.onmousemove = debounce(function () {
            oBox.innerHTML = num++
        }, 1000)
    </script>
</body>

</html>
<!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>
</head>

<body>
    <input type="text" id="text">
    <div id="box"></div>
    <script>
        // 节流
        // 函数在n秒内执行一次,在n秒内重复操作也不会重复执行,到时间就会执行
        // 一个函数5秒内执行一次,即使重复操作,间隔5秒就会自动执行
        // 坐公交车 30分钟一班
        // throttle 
        // 定义一个节流函数
        function throttle(callback, time) {
            var obj = {}
            var timer = null
            var fn = function () {
                callback.apply(obj)
            }
            var nowTime = Date.now() //获取当前时间戳
            return function () {
                obj = this
                var oTime = Date.now() //在获取一个时间
                var awaitTime = oTime - nowTime - time
                if (awaitTime > 0) {
                    nowTime = oTime
                    timer = setTimeout(fn, time)
                }
            }
        }

        var oText = document.querySelector("#text")
        var oBox = document.querySelector("#box")
        oText.addEventListener("input", throttle(function () {
            oBox.innerHTML = oText.value
        }, 3000))

    </script>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值