summaryrefslogtreecommitdiff
path: root/source/_posts/实时搜索中的防抖函数.md
diff options
context:
space:
mode:
Diffstat (limited to 'source/_posts/实时搜索中的防抖函数.md')
-rw-r--r--source/_posts/实时搜索中的防抖函数.md79
1 files changed, 79 insertions, 0 deletions
diff --git a/source/_posts/实时搜索中的防抖函数.md b/source/_posts/实时搜索中的防抖函数.md
new file mode 100644
index 00000000..13e9f28d
--- /dev/null
+++ b/source/_posts/实时搜索中的防抖函数.md
@@ -0,0 +1,79 @@
+---
+title: 实时搜索中的防抖函数
+date: 2025-02-10 11:34:18
+tags: [Technique]
+---
+
+在实现实时搜索功能时,通常会使用输入框的事件监听器来捕获用户的输入变化,并在输入变化时发送搜索请求。为了避免过多的请求导致服务器负担过重,通常会使用“防抖”(debounce)技术来控制请求的频率。
+
+### 实现步骤
+
+1. 监听输入框的变化:使用`input`事件监听器来捕获用户的输入变化。
+2. 防抖处理:使用防抖函数来限制请求的频率。防抖函数会在用户停止输入一段时间后才发送请求。
+3. 发送请求:在防抖函数中调用搜索请求。
+
+### 防抖函数示例
+
+以下是一个简单的防抖函数示例:
+
+```javascript
+function debounce(func, wait) {
+ let timeout;
+ return function(...args) {
+ const context = this;
+ clearTimeout(timeout);
+ timeout = setTimeout(() => func.apply(context, args), wait);
+ };
+}
+```
+
+### 实现实时搜索
+
+假设你有一个输入框用于搜索患者:
+
+```svelte
+<script>
+ import { onMount } from 'svelte';
+ import { patientsStore } from '$lib/stores/patients.svelte';
+
+ let searchTerm = '';
+
+ // 防抖函数
+ function debounce(func, wait) {
+ let timeout;
+ return function(...args) {
+ const context = this;
+ clearTimeout(timeout);
+ timeout = setTimeout(() => func.apply(context, args), wait);
+ };
+ }
+
+ // 搜索函数
+ const searchPatients = debounce(async (term) => {
+ if (term) {
+ // 发送搜索请求
+ const response = await fetch(`/api/search-patients?query=${term}`);
+ const data = await response.json();
+ patientsStore.mbglPatients = data;
+ } else {
+ // 清空搜索结果或恢复默认数据
+ patientsStore.mbglPatients = [];
+ }
+ }, 300); // 300ms 的防抖时间
+
+ // 监听输入框变化
+ function handleInput(event) {
+ searchTerm = event.target.value;
+ searchPatients(searchTerm);
+ }
+</script>
+
+<input type="text" placeholder="搜索患者..." on:input={handleInput} bind:value={searchTerm} />
+```
+
+### 请求发送间隔
+
+- 防抖时间:通常设置为 300ms 到 500ms 之间。这个时间足够让用户完成输入并减少不必要的请求。
+- 考虑用户体验:防抖时间过短可能导致过多请求,过长则可能让用户感到延迟。300ms 是一个常用的折中值。
+
+通过这种方式,你可以实现一个高效的实时搜索功能,既能保证用户体验,又能减少服务器的负担。