前端 防抖(Debouncing)
防抖(Debouncing)
是一种在前端开发中常用的技术,特别是与事件处理相关时。防抖技术的核心思想是:在事件被频繁触发时,只在最后一次事件触发后的一段指定时间内执行一次回调函数,如果在这个时间内又触发了事件,那么重新计时。
防抖的用途
防抖技术通常用于以下场景:
-
文本输入:如搜索框输入时的自动完成功能,避免每次输入都发送请求。
-
窗口调整:如浏览器窗口大小调整时的事件处理。
-
滚动事件:如无限滚动加载更多内容时,避免在滚动过程中频繁触发事件。
防抖的原理
防抖的原理是使用 setTimeout
来延迟函数的执行。当事件被触发时,会清除之前的定时器,并重新设置一个新的定时器。如果在定时器到期之前再次触发事件,那么之前的定时器会被取消,并重新设置一个新的定时器。
防抖函数的实现
下面是一个简单的防抖函数的实现:
function debounce(fn, delay) {
let timeoutId = null;
return function(...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
示例:文本输入防抖
假设我们有一个搜索框,用户输入时会触发搜索建议的请求。我们不希望每次用户输入时都发送请求,而是希望在用户停止输入一段时间后再发送请求。
// 模拟搜索建议的函数
function searchSuggestions(query) {
console.log(`搜索建议:${query}`);
}
function debounce(fn, delay) {//防抖函数
let timeoutId = null;
return function(...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// 创建防抖版本的搜索建议函数
const debouncedSearchSuggestions = debounce(searchSuggestions, 300);
// 绑定到输入框的事件
const searchInput = document.getElementById('search-input');
searchInput.addEventListener('input', (event) => {
debouncedSearchSuggestions(event.target.value);
});
- 当用户在搜索框中输入时,
input
事件会被触发。 - 每次事件触发时,都会调用
debouncedSearchSuggestions
函数。 - 这个函数会延迟执行
searchSuggestions
函数,延迟时间为 300 毫秒。 - 如果用户在 300 毫秒内继续输入,之前的定时器会被取消,并重新设置一个新的定时器。
- 只有当用户停止输入超过 300 毫秒后,
searchSuggestions
函数才会被执行。
实现vue中input不使用v-model 实现input防抖
<script setup lang="ts">
import { ref, version as vueVersion } from 'vue'
let text=ref('')
function fd(fn, delay) {//防抖函数
let timeoutId = null;
return function (...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
function handleInput(value){ //输入更新
text.value=value.target.value
}
const fdinpout=fd(handleInput,3000) //3秒防抖输入更新
</script>
<template>
<h1>{{ text }}</h1>
<input :value="text" @input="fdinpout"> //不使用v-model 拆成 :value 和input函数
</template>