JS技能 节流和防抖

发布于:2024-03-29 ⋅ 阅读:(16) ⋅ 点赞:(0)

概念:

说起节流防抖,大多数人首当其冲地说:防抖是一段时间内以最后一次动作执行为准,节流是,一段时间内以第一次执行动作为准。这么说没毛病,但这是从现象来总结的。问题来了:什么是节流、什么是防抖呢?

防抖(debounce):是指在事件触发后,延迟一定时间在执行回调函数,如果在延迟时间内又触发了该事件,则重新计时。

思路:事件要用到函数,延迟一定时间所以要用到定时器,需要知道在延迟的时间是否又触发了该事件要用到闭包


<!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="useript">
    <script>
        var ipt = document.getElementById("useript");
        ipt.onkeyup=debounce(function(e){
            console.log(e);
        },1000);
        function debounce(fn, delay) {
            //这样子建立了一个闭包,timer始终存在
            var timer = null;
            // 这里返回的函数是每次用户实际调用的防抖函数
            return function (...args) {
               //如果已经设定过定时器了就清空上一次的定时器
                if (timer) {
                    clearTimeout(timer); //清除上一次的
                }
                timer = setTimeout(function () {
                    fn(...args)
                    timer = null;
                }, delay);
            }
        }
    </script>
</body>
</html>

节流(debounce):是指在一定时间内,只执行一次回调函数,如果在该时间段内多次触发该事件,只有第一触发会执行回调函数,后续的触发会被忽略。

思路:每次事件被触发时,如果函数没有在指定的时间间隔内被调用过,则调用函数并设置一个计时器。如果在指定的时间间隔内再次触发了事件,则不调用函数,直到指定的时间间隔过去,重新开始调用函数。

<!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></title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: relative;
            top: 100px;
        }
    </style>
</head>

<body>
    <div class="box">
    </div>
    <script>
        var box = document.querySelector(".box");
        window.onmousemove = throttleMy(function (e) {
            box.style.left = e.pageX - (box.clientWidth) / 2 + "px";
            box.style.top = e.pageY - (box.clientHeight) / 2 + "px";
        }, 10)
        function throttleMy(fn, delay) {
            //这样子建立了一个闭包,timer始终存在
            var timer = null;
            return function (...args) {
                if (timer) {
                    return;// 只执行上一次
                }
                timer = setTimeout(function () {
                    fn(...args)
                    timer = null;
                }, delay);
            }
        }
    </script>
</body>

</html>

本文含有隐藏内容,请 开通VIP 后查看