From ad8f9f55ea79a4d587aecc69698808da82de3d62 Mon Sep 17 00:00:00 2001 From: somhairle Date: Tue, 21 Apr 2026 20:40:27 +0800 Subject: 二〇二六年四月二十一日 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...230\262\346\212\226\345\207\275\346\225\260.md" | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 "source/_posts/\345\256\236\346\227\266\346\220\234\347\264\242\344\270\255\347\232\204\351\230\262\346\212\226\345\207\275\346\225\260.md" (limited to 'source/_posts/实时搜索中的防抖函数.md') diff --git "a/source/_posts/\345\256\236\346\227\266\346\220\234\347\264\242\344\270\255\347\232\204\351\230\262\346\212\226\345\207\275\346\225\260.md" "b/source/_posts/\345\256\236\346\227\266\346\220\234\347\264\242\344\270\255\347\232\204\351\230\262\346\212\226\345\207\275\346\225\260.md" new file mode 100644 index 00000000..13e9f28d --- /dev/null +++ "b/source/_posts/\345\256\236\346\227\266\346\220\234\347\264\242\344\270\255\347\232\204\351\230\262\346\212\226\345\207\275\346\225\260.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 + + + +``` + +### 请求发送间隔 + +- 防抖时间:通常设置为 300ms 到 500ms 之间。这个时间足够让用户完成输入并减少不必要的请求。 +- 考虑用户体验:防抖时间过短可能导致过多请求,过长则可能让用户感到延迟。300ms 是一个常用的折中值。 + +通过这种方式,你可以实现一个高效的实时搜索功能,既能保证用户体验,又能减少服务器的负担。 -- cgit v1.2.3