summaryrefslogtreecommitdiff
path: root/source/_posts/实时搜索中的防抖函数.md
blob: 13e9f28d1dfacf691aa5c0c102f2c7f18814f281 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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 是一个常用的折中值。

通过这种方式,你可以实现一个高效的实时搜索功能,既能保证用户体验,又能减少服务器的负担。