前因
浏览器中比较高频响应,resize/scroll/touchmove 响应函数复杂一些 会跟不上触发频率,便会出现页面卡顿,延迟,假死鞥现象
场景
搜索框查询
输入框联想
表单验证
提交按钮
代码实现(其实就是防抖稍微改动下触发事件罢了)
<!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 throttle = function (fun, delay) {
let timeout
return function() {
// timeout && clearTimeout(timeout)
// 解决事件函数绑定中this
let that = this
// 绑定事件中 事件函数的传递
let argus = arguments
// timeout = setTimeout(() => {
// //fun.apply(that, argus)
// console.log('>>>>>>[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]', this)
// fun(argus)
// }, delay);
if (!timeout) {
timeout = setTimeout(() => {
fun.apply(that, argus)
timeout = null
}, delay);
}
}
}
function fun(e) {
count++
console.log('>>>>>>>>>>>>', e, this)
e.target.innerText = count
}
let count = 0
document.querySelectorAll('.box')[0].addEventListener('mousemove', throttle((e) => {
count++
console.log('>>>>>>>>>>>>', e, this)
e.target.innerText = count
}, 1000))
</script>
</body>
</html>