防抖函数(最全 最干净 最好理解)
1.应用场景
1.input输入框 输入远程查询
2.邮箱,手机号验证,用户名验证
3.resize等高评率场景
2.解决问题
高频场景带来的重复渲染 等问题
多次操作 只在操作结束后再执行操作函数
3.具体实现
3.1this问题(因为settimeout是window的对象 所以函数中this指向window 除非箭头函数)
1.事件函数里的this才指向box
错误示范:return里面的this 与函数体内的this指向 在不同场景中 指向并不相同
解决方案: 可以使用 fun.call(this) 来重定向函数中this的指向 【call 传参是单个】
3.2事件对象
1.arguments 作为函数的关键字,它接收的是这个函数传递的所有实参,包括这个事件对象
因为事件对象是默认传递的参数,因为call只能传递一个参数,所以我们选择使用 fun.apply(this, args)
3.3具体代码实现
<!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><style>html {height: 100%;}body {display: flex;height: 100%;justify-content: center;align-items: center;}.box {width: 100px;height: 100px;text-align: center;line-height: 100px;background: #FF9800;color: #fff;}</style>
</head>
<body><div class="box"> 0 </div><script>const debounce = function (fun, delay) {let timeoutreturn function() {timeout && clearTimeout(timeout)// 解决事件函数绑定中thislet that = this// 绑定事件中 事件函数的传递let argus = argumentstimeout = setTimeout(() => {fun.apply(that, argus) }, delay);}}function fun(e) {count++console.log('>>>>>>>>>>>>', e, this)e.target.innerText = count}let count = 0console.log()document.querySelectorAll('.box')[0].addEventListener('mousemove', debounce(fun, 300))</script>
</body>
</html>