If you were building a search tool and wanted search results to pop up as you typed, write a function that gets called on every key down but calls the server when the user stops typing for 400ms.
阿神2017-04-10 14:55:45
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 |
|
高洛峰2017-04-10 14:55:45
监听事件 -> 读前端cache ? 构建结果列表 : (发请求拿结果 -> cache并构建结果列表)
400ms 可以用计时器做 delay 处理,根据事件触发情况看是进后面流程还是 clear 掉。
迷茫2017-04-10 14:55:45
哈,我也搞過這種東西,處理辦法也是同樣的。
之所以這樣,是因爲你會發現在用戶高速鍵入的時候發出的請求很多,卻只有最後一個纔有意義。況且實時感也只是在你停頓的時候才能顯現出來。
所以這一 debounce 可以很有效地改善體驗。
具體實現,除了 debounce 就是 ajax,隨便找個庫比如 underscore 都會提供。
原理如樓上代碼,就是對每次事件先 clearTimeout 再 setTimeout。
http://www.glassdoor.com/Interview/If-you-were-building-a-search-tool-and-wanted-search-results-to-pop-up-as-you-typed-but-the-server-call-was-taxing-write-a-QTN_835901.htm