前言
防抖和节流函数目前已经是前端实际开发中两个非常重要的函数,也是面试经常被问到的面试题,我们会一起来学习防抖和节流函数。
一、认识防抖debounce函数
- 我们用一副图来理解一下它的过程:
二、使用步骤
1.代码演示
代码如下(示例):
index.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">
<script src="./debounce的基本实现/01_debounce.js"></script>
<script>
const inputEl = document.querySelector("input")
const inputChangeg = function (event) {
console.log("发送了网络请求!",this,event);
}
// 防抖处理:传入两个参数,一个执行的函数,一个延迟的事件
inputEl.oninput = debounce(inputChangeg,2000)
</script>
</body>
</html>
js代码
//fn 需要执行的函数
// delay: 需要延迟多长时间
function debounce (fn, delay) {
// 定义一个定时器,保存上一次的定时器(timer是个数字)
let timer = null
// 发生事件,真正执行的函数
const _debounce = function (...args) {
// 取消上一次的定时器
if (timer) clearTimeout(timer)
//settimeout 会返回一个返回值timer
// 延迟执行
timer = setTimeout(() => {
// 外部传入的真正执行的函数
fn.apply(this,args)//注意这里有this的绑定与参数的传递
}, delay);
}
return _debounce
}
总结
coderwhy老师讲的debounce的基本使用,注意这里面有this的绑定与参数的传递。