js中防抖 debounce 节流 throttle 原理 从0手动实现

news/2024/9/29 18:20:58 标签: javascript, 前端, 开发语言

1 防抖

        高频触发事件时,执行损耗高的操作,连续触发过程中,只执行最后一次

  1. 高频事件:input scroll resize等。
  2. 损耗高:网络请求、dom操作。

         实现防抖步骤:1.在回调函数中判断timer是否存在,存在就清理计时器,重新计时执行。2.在实现debounce函数时,注意返回函数和传入的函数参数都不能时回调函数,否在造成this丢失。3. debounce函数中返回函数顶层使用this保存,回调函数使用apply调用。 4.要使传递参数可行,顶层函数解构赋值参数,然后再回调apply时传入参数(注意不需要解构,...args时就是个数组)。

javascript">// 防抖: 防止js函数在短时间内被频繁调用,减少性能消耗以及视觉抖动或者网络消耗服务器资源
// 防抖原理:再触发频率高的事件中,执行耗费性能的操作,连续操作后,只有最后一次操作生效
// 频率高的事件:resize, input, scroll, mousemove, mouseover, mouseout, keyup, keydown, keypress
// 耗费性能的操作:dom操作,网络请求

// 事件触发后,延迟一段时间执行函数,如果在这段时间内再次触发事件,则重新计时
let timer = null
document.getElementById('btn').addEventListener('click' , ()=>{
    timer && clearTimeout(timer)
    timer = setTimeout(()=>{
        console.log('click__debounce')
    }, 500)
})

// 也可以使用lodash库中的debounce方法,lodash(func, [wait=0], [options={}])
class _ {
    static debounce(callback, wait){
        let timer = null
        // 返回不能使用箭头函数,否则无法获取this中的dom元素
        return function(...args){
            // 存储调用时的this(一般是dom元素)
            const _this = this
            timer && clearTimeout(timer)
            timer = setTimeout(()=>{
                // 通过apply将this指向调用时的dom元素
                callback.apply(_this, args)
            }, wait)
        }
    }
}

// 传入函数不能使用箭头函数,否则无法绑定this
const debounceFunc = _.debounce(function(e){
    console.log(e)
    console.log(this)
    console.log('input')
}, 500)

document.querySelector('input').addEventListener('input', debounceFunc)

2 节流

        高频触发事件时,执行损耗高的操作,连续触发过程中,在设置好的单位时间内只执行一次

        流程和防抖类似,区别在于每次判断定时器是否存在,如果存在就不执行任何操作,如果定时器不存在,那么需要重新设置定时器,并且再定时器的回调函数内部执行末尾清除定时器。代码如下所示:

javascript">// 节流: 频繁触发事件时,减少触发次数,提高性能
// 例如:视频播放时 保存播放进度
// 防抖原理:再触发频率高的事件中,执行耗费性能的操作,连续操作后,单位事件内只有一次生效
// lodash库中的throttle方法,lodash(func, [wait=0], [options={}])
let timer_t = undefined
document.getElementById('btn_t').addEventListener('click', () => {
    if(!timer_t){
        timer_t = setTimeout(()=>{
            console.log('click throttle')
            timer_t = undefined
        }, 1000)
    }
})


_.throttle = function(callback, wait){
    let timer = undefined
    return function(...args){
        _this = this
        if(!timer){
            timer = setTimeout(()=>{
                callback.apply(_this, args)
                timer = undefined
            }, 1000)
        }
    }
}

const throttleFunc = _.throttle(function(e){
    console.log(this)
    console.log(e)
    console.log("click throttle")
})


document.getElementById('input_t').addEventListener('input', throttleFunc)

3 配套文件index.html

        新建index.js将上述代码拷贝即可在控制台查看效果,index.html内容如下:

<!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>
<div>
    <button id="btn">click_debounce</button>
    <button id="btn_t">click_throttle</button>
    <input type="text" id="input">
    <input type="text" id="input_t">
    <script src="08_index.js"></script>
</div>
</body>
</html>

http://www.niftyadmin.cn/n/5683514.html

相关文章

docker kibana 连接es

server.name: kibana server.host: “0” #容器中配置&#xff0c;去掉http://127.0.0.1:9200 elasticsearch.hosts: [“http://host.docker.internal:9200”] #设置访问用户 elasticsearch.username: “elastic” #设置访问密码 elasticsearch.password: “elastic” #设置中文…

TCP编程:从入门到实践

目录 一、引言 二、TCP协议原理 1.面向连接 2.可靠传输 三、TCP编程实践 1.TCP服务器 2.TCP客户端 四、总结 本文将带你了解TCP编程的基本原理&#xff0c;并通过实战案例&#xff0c;教你如何在网络编程中运用TCP协议。掌握TCP编程&#xff0c;为构建稳定、高效的网络通信…

服务器使用frp做内网穿透详细教程,请码住

目录 1.内网穿透的定义 2.前提条件 3.frp下载地址 4.配置服务器端的frps.toml文件 5. 配置客户端&#xff0c;即物理服务器或者是电脑本机地址 6.添加服务端启动命令startServerFrp.sh 7.添加客户端启动命令startClientFrp.sh 8. 查看服务端启动日志 9.查看客户端启…

【算法】反向传播算法

David Rumelhart 是人工智能领域的先驱之一&#xff0c;他与 James McClelland 等人在1986年通过其著作《Parallel Distributed Processing: Explorations in the Microstructure of Cognition》详细介绍了反向传播算法&#xff08;Backpropagation&#xff09;&#xff0c;这一…

哈希表(HashMap、HashSet)

文章目录 一、 什么是哈希表二、 哈希冲突2.1 为什么会出现冲突2.2 如何避免出现冲突2.3 出现冲突如何解决 三、模拟实现哈希桶/开散列&#xff08;整型数据&#xff09;3.1 结构3.2 插入元素3.3 获取元素 四、模拟实现哈希桶/开散列&#xff08;泛型&#xff09;4.1 结构4.2 插…

python绘制动态残差图,plot交互模式

python绘制动态残差图 动态刷新数据&#xff0c;交互模式 # 开启交互模式plt.ion()# 创建初始数据x_line [0, 1]err_wage [0, 10]# 创建图形和轴fig, ax plt.subplots()line, ax.plot(x_line, err_wage, b-) # b-表示蓝色实线# ax.set_xlim(0, 20) # 设置x轴的范围# ax.…

甘肃非遗文化网站:Spring Boot开发实战

3 系统分析 当用户确定开发一款程序时&#xff0c;是需要遵循下面的顺序进行工作&#xff0c;概括为&#xff1a;系统分析–>系统设计–>系统开发–>系统测试&#xff0c;无论这个过程是否有变更或者迭代&#xff0c;都是按照这样的顺序开展工作的。系统分析就是分析系…

什么是SQL注入?

SQL注入是一种安全漏洞&#xff0c;攻击者通过在应用程序的输入字段中插入恶意SQL代码&#xff0c;从而操控数据库。此类攻击通常利用应用程序未对用户输入进行适当验证和清理的弱点。 工作原理&#xff1a; 输入字段&#xff1a;攻击者在登录表单或搜索框等输入区域插入恶意…