防抖的含义是在一定时间内,事件被触发多次,只有最后一次生效,前面的都被取消。比如在搜索框输入关键词时,只有当用户停止输入一段时间后,才发送请求,避免每输入一个字符就发送一次请求。
//防抖
<input type="text">
<script>
const ip = document.querySelector('input')
// ip.addEventListener('input', function () {
// console.log(ip.value);
// })
function debounce(fun, time) {
let timer
return function () {
clearTimeout(timer)
timer = setTimeout(() => {
fun()
}, time)
}
}
ip.addEventListener('input', debounce(() => {
console.log(ip.value);
}, 500))
</script>
节流的含义是在一定时间内,事件被触发多次,只有第一次生效,后面的都被忽略。比如在滚动加载更多数据时,只有当用户滚动到底部时,才发送请求,避免每滚动一段距离就发送一次请求。
//节流
<input type="text">
<script>
const ip = document.querySelector('input')
// ip.addEventListener('input', function () {
// console.log(ip.value);
// })
function thorttle(fun, time) {
let timer = null
return function () {
if (!timer) {
timer = setTimeout(() => {
fun()
clearTimeout(timer)
timer = null
}, time);
}
}
}
ip.addEventListener('input', thorttle(() => {
console.log(ip.value);
}, 500))
</script>