防抖(debounce):
概念:指触发事件后的n秒内函数只会执行一次,如果在n秒内再次触发事件,则会重新计时n秒。
使用场景:输入框输入
手写代码:
<!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>手写防抖</title>
</head>
<body>
输入框:<input type="text" onkeydown="handleClick(event)" />
</body>
<script>
function handleClick(event) {
_debounce(fnCallback, 10000)
}
function fnCallback() {
console.log('开始搜索')
}
var timer = null
function _debounce(fn, delay) {
console.log('监听到输入')
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fn()
}, delay);
}
</script>
</html>
节流(throttle):
概念:指在n秒内多次触发事件,只会执行一次。
使用场景:按钮点击
手写代码:
<!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>手写节流</title>
</head>
<body>
<button id="myBtn" onclick="handleClick()">点击</button>
</body>
<script>
function handleClick(){
console.log(123);
_throttle(fnCallback,3000)
}
function fnCallback() {
console.log('开始搜索')
}
var timer = null
function _throttle(fn,delay){
if(!timer){
timer = setTimeout(() => {
fn()
clearTimeout(timer)
timer = null
}, delay);
}
}
</script>
</html>