延迟搜索 延时搜索
How to delay the .keyup() handler until the user stops typing?
I use this small function for the same purpose, executing a function after the user has stopped typing for a specified amount of time or in events that fire at a high rate, like resize
:
function delay(callback, ms) { var timer = 0; return function() { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, ms || 0); }; } // Example usage: $('#input').keyup(delay(function (e) { console.log('Time elapsed!', this.value); }, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="input">Try it: <input id="input" type="text" placeholder="Type something here..."/> </label>
How it works:
The delay
function will return a wrapped function that internally handles an individual timer, in each execution the timer is restarted with the time delay provided, if multiple executions occur before this time passes, the timer will just reset and start again.
When the timer finally ends, the callback function is executed, passing the original context and arguments (in this example, the jQuery's event object, and the DOM element as this
).
UPDATE 2019-05-16
I have re-implemented the function using ES5 and ES6 features for modern environments:
function delay(fn, ms) {
let timer = 0
return function(...args) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, ...args), ms || 0)
}
}
The implementation is covered with a set of tests.
For something more sophisticated, give a look to the jQuery Typewatch plugin.
另外一个人写了一个jQuery的插件,
AJAX: Delay for search on typing in form field [duplicate]
var delayTimer;
function doSearch(text) {
clearTimeout(delayTimer);
delayTimer = setTimeout(function() {
// Do the ajax stuff
}, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
}
相关文章
- ElasticSearch NEST搜索
- Java实现 LeetCode 173 二叉搜索树迭代器
- Java实现 LeetCode 74 搜索二维矩阵
- LeetCode(95): 不同的二叉搜索树 II
- CRM product搜索结果重复数据的一个解决方案
- Atitit btree 搜索原理 目录 第一节 左边小右边大 的有序树1 第二节 平衡算法1 第三节 层次高度一般3--4层3 第四节 类似索引3 第二章 Ref5 第一节 左边小右
- Atitit.软件gui按钮and面板---os区-----linux windows搜索文件 文件夹
- vuejs搜索关键字高亮显示并且实现切换显示下一个选项多种方法
- 938. 二叉搜索树的范围和
- 大约SQL/NoSQL数据库搜索/思考查询
- L34.linux命令每日一练 -- 第五章 Linux信息显示与搜索文件命令 -- echo和watch
- pip 搜索安装包、查看已经安装模块、
- 力扣:BFS广度优先搜索
- [Elasticsearch] 多字段搜索 (五) - 以字段为中心的查询