[英]In jquery how can I call function when someone hasn't typed in 1 second?
I have a <div>
that has a list of items being load()
ed into it containing a keyword typed in a text input triggered by keyup()
. 我有一个
<div>
,其中包含要load()
到其中的项目的列表,其中包含在由keyup()
触发的文本输入中键入的关键字。 When I also run a jquery plugin that highlights that keyword in the respective search items on keyup() it slows the page WAY down and can even crash my browser. 当我还运行一个jquery插件时,该插件会在keyup()的相应搜索项中突出显示该关键字,这会使页面的运行速度变慢,甚至会使我的浏览器崩溃。
So I'm wondering if there is a way that I can only trigger this highlighting function after a person hasn't typed any characters in a second or two and THEN trigger the highlighter. 因此,我想知道是否存在一种方法,只有在一个人没有在一两秒钟内键入任何字符,然后触发荧光笔后,才可以触发该荧光笔功能。 Or is there maybe some way I can keep it at the end of the queue so that it always triggers last?
还是有某种方法可以将其保留在队列的末尾,以便它总是在最后触发?
thx 谢谢
Keep a global timeout variable like var myTimeout = null;
保留全局超时变量,如
var myTimeout = null;
. 。 Inside your keyup() handler, you can start a
myTimeout = window.setTimeout(highlight, 1500);
在keyup()处理程序中,您可以启动
myTimeout = window.setTimeout(highlight, 1500);
and cancel the (previous) timeout if it is still running. 并取消(以前的)超时(如果它仍在运行)。 Inside the highlight function you reset myTimeout to null again.
在高亮功能内,将myTimeout再次重置为null。
Something in the lines of 某些东西
var myTimeout = null;
$('#whatever').keyup(function() {
if(myTimeout) clearTimeout(myTimeout);
....
myTimeout = window.setTimeout(highlight, 1500);
});
function highlight() {
myTimeout = null;
...
}
Use setTimeout
to set the function to run after 2s and user clearTimeout
to cancel this before the 2s are finished: 使用
setTimeout
将功能设置为在2秒后运行,并使用clearTimeout
在2秒结束前取消此功能:
var timeoutId;
$("input").keyup(function(){
if(timeoutId){
clearTimeout(timeoutId);
}
timeoutId = setTimeout(intervalFunc, 2000);
});
Here's an example: http://jsfiddle.net/tdbsY/ 这是一个示例: http : //jsfiddle.net/tdbsY/
You want to use setTimeout
to delay the call to highlight, and clearTimeout
if a new keystroke is received before that one second has passed: 您想使用
setTimeout
来延迟突出显示的调用,如果在经过一秒钟之前收到了新的击键,请使用clearTimeout
:
var timeout;
$('#my-input').keyup(function() {
// clear previous timeout if there was one
window.clearTimeout(timeout);
// set new one
timeout = setTimeout(function() {
// make your highlight call here
}, 1000);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.