封装防抖(debounce)函数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            margin: 20px auto;
            width: 500px;
            height: 500px;
            border: 1px solid red;
        }
    </style>
</head>

<body>
    <div id="dv"></div>
    <script>
        const dv = document.getElementById('dv')

        /* 
       封装防抖函数
       */
        function debounce(callBack, time) {
            // callBack: 传入的回调函数
            // time: 定时器的第二个参数(多长时间触发)
            // 存放定时器的Id
            let timer = null
            return function () {
                // 通过定时器Id清除定时器
                clearTimeout(timer)
                // 将定时器的返回值 定时器Id 存到 timer 中
                timer = setTimeout(() => {
                    // 通过 apply 改变传入的回调函数 callBack 的 this 指向
                    // 通过 arguments 拿到外层函数的事件对象(箭头函数没有 this 指向)
                    // 注意:事件处理函数只能有一个形参(拿到事件对象),
                    // 如果要传多个参数,方法:在外面封装一个函数,在事件处理函数中调用
                    callBack.apply(this, arguments)
                }, time)
            }
        }

        dv.onmousemove = debounce(function (e) {
            this.innerHTML = `x的坐标为${e.pageX},y的坐标为${e.pageY}`
        }, 100)

    </script>
</body>

</html>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TypeScript(简称TS)是一种由微软开发的开源编程语言,它是JavaScript的一个超集,可以编译成纯JavaScript代码。在TS中,我们可以使用装饰器和泛型等特性来封装防抖节流函数防抖函数和节流函数都是用于控制函数执行频率的方法,常用于优化性能和避免重复触发事件。 防抖函数的作用是在一定时间内,如果事件持续触发,则重新计时,直到事件停止触发后才执行函数。常见的应用场景是输入框搜索联想功能。 节流函数的作用是在一定时间内,无论事件触发多少次,只执行一次函数。常见的应用场景是滚动加载数据。 下面是一个使用TS封装防抖节流函数的示例: ```typescript // 防抖函数 function debounce(func: Function, delay: number): Function { let timer: number | null = null; return function (...args: any[]) { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { func.apply(this, args); }, delay); }; } // 节流函数 function throttle(func: Function, delay: number): Function { let timer: number | null = null; return function (...args: any[]) { if (!timer) { timer = setTimeout(() => { func.apply(this, args); timer = null; }, delay); } }; } ``` 使用示例: ```typescript function search(keyword: string) { // 模拟搜索功能 console.log(`Searching for ${keyword}`); } const debouncedSearch = debounce(search, 300); const throttledSearch = throttle(search, 300); debouncedSearch('apple'); debouncedSearch('banana'); debouncedSearch('cherry'); throttledSearch('apple'); throttledSearch('banana'); throttledSearch('cherry'); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值