【js知识点】js节流和防抖

js节流和防抖


一、防抖

  1. 目的是为了防止事件频繁触发,节省性能消耗
  2. 防抖主要应用于表单输入事件等容易频繁触发的事件中
  3. 防抖的主要特点是多次触发同一事件只有最后一次会生效

以表单input事件触发的请求案例为例子:
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>2022-8-23</title>
</head>
<body>
    <input type="text" id="debouce">
    <script src="../2022-8-23.js"></script>
</body>
</html>

js中代码


let request = function(value) {
    console.log('请求的数据:', value);
};

// 防抖
const debounce = function(fn, delay = 500) {
    let timer = null;
    let content = this;
    return function(...ags) {
        if(timer) {
            clearTimeout(timer);
            timer = null;
        } else {
            fn.apply(content, ags);
        };
        timer = setTimeout(() => {
            fn.apply(content, ags);
        }, delay);
    }
}

const inputFn = function (e) {
    let value = e.target.value;
    request(value);
}
document.querySelector("#debouce").oninput = debounce(inputFn, 1000);

二、节流

  1. 目的是为了防止事件频繁触发,节省性能消耗
  2. 防抖主要应用于滚动事件等容易频繁触发的事件中
  3. 防抖的主要特点是多次触发同一事件只有第一会生效

以scroll事件触发的请求案例为例子:
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 style="width: 100%;height: 4000px;background: rgba(49, 135, 9, 0.563);">
<script src="../2022-8-26.js"></script>
</body>
</html>

js中代码

// 节流

// 核心思想:
// 1、在一定的时间范围内执行一次函数
// 2、部分逻辑和防抖一致
let scrollEvevtCount = 0;

let scrollFn = function() {
    scrollEvevtCount++;
    console.log('scroll事件触发:', scrollEvevtCount)
};


let throttle = function(fn, delay) {
    let timer = null;
    let pre = new Date().getTime();
    return function(...ags) {
        let now = new Date().getTime();
        if (now - pre > delay) {
            timer = setTimeout(function() {
                fn.apply(this, ags);
                pre = now;
                clearTimeout(timer);
            }, delay);
        }
    }
}

let throttle2 = function(fn, delay) {
    let content = this;
    let timer = null;
    let lock = false;
    return function () {
        if (!lock) {
            lock = true;
            timer = setTimeout(function() {
                fn.apply(content, arguments);
                clearTimeout(timer);
                lock = false;
            }, delay);
        }
    }
}


document.body.onscroll = throttle(scrollFn, 500);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LuckyCola2023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值