等待功能,直到用户停止打字 [英] Wait for function till user stops typing

查看:132
本文介绍了等待功能,直到用户停止打字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用户在打字时拨打电话。问题是它使每一个字母都被打字,所以我设置这样的超时:

I have users making ajax call while typing. The problem is that it makes the call for every letter being typed, so I set timeout like this:

$(input).live('keyup', function(e){

setTimeout(function(){ 

var xx = $(input).val();
doSearch(xx); 

}, 400); 

}); 

它等待400ms,然后执行每个按键。在最后输入一封信后约400ms的时候,如何更改这个ajax调用只有一次?

It does wait for 400ms but then executes for every keyup. How can I change this to make the ajax call only 'once' about 400ms after the last typed letter?

(我过去使用'delay',但是根本不符合我的脚本...)

(I used 'delay' in the past but that doesn't work at all with my script...)

推荐答案

timer = 0;
function mySearch (){ 
    var xx = $(input).val();
    doSearch(xx); 
}
$(input).live('keyup', function(e){
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(mySearch, 400); 
});

最好将函数移动到命名函数并多次调用,因为否则在每个加密上重新创建另一个lambda函数,这是不必要的且相对昂贵的

it's better to move your function to a named function and call it multiple times, 'cause otherwise you're creating another lambda function on each keyup which is unnecessary and relatively expensive

这篇关于等待功能,直到用户停止打字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆