直接附演示代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>防抖与节流</title>
</head>
<body>
<div>
防抖:<input type="text" id="input1"> <span id="value1"></span>
</div>
<div>
节流:<input type="text" id="input2"> <span id="value2"></span>
</div>
<script>
/************************
防抖
概念:函数触发后延迟一段时间再执行,如果在这期间又被触发,则重新计时
常用场景:搜索框输入减少查询量(用户输入完,即无操作时调用接口,而不是每输入一个字符就调用接口)
*************************/
function debounce(func, delay) {
return function() {
const _this = this
const _args = arguments
clearTimeout(func.did)
func.did = setTimeout(function() {
func.call(_this, [..._args])
}, delay)
}
}
function handleInput1KeyUp(value) {
const valueText = value.join()
document.querySelector('#value1').innerText = valueText
}
const debounceHandleKeyUp = debounce(handleInput1KeyUp, 500)
document.querySelector('#input1').addEventListener('keyup', function(e) {
debounceHandleKeyUp(e.target.value, '参数2', '参数3')
})
/************************
节流
概念:一段时间内函数只触发一次
常用场景:监听鼠标滚动事件,执行触底加载效果(滚动一段时间就调用一次接口,而不是滚动时一直调用接口,也不是像防抖那样,滚动结束后再调用接口)
*************************/
function throttle(func, delay) {
let last;
return function() {
const _this = this
const _args = arguments
const now = +new Date()
if (last && now < last + delay) {
clearTimeout(func.tid)
func.tid = setTimeout(function() {
last = now
func.call(_this, [..._args])
}, delay)
} else {
last = now
func.call(_this, [..._args])
}
}
}
function handleInput2KeyUp(val) {
const valueText = val.join()
document.querySelector('#value2').innerText = valueText
}
const throttleHanleInputKeyUp = throttle(handleInput2KeyUp, 500)
document.querySelector('#input2').addEventListener('keyup', function(e) {
throttleHanleInputKeyUp(e.target.value, '参数二', '参数三')
})
</script>
</body>
</html>