Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

timer - Jquery Run code 2 seconds after last keypress

I am working on a auto search function for a site.

It uses ajax to query an api.

At the moment after 3 characters are entered it will search on every key press.

What I want is

Case1:
User enters tes
2 seconds pass search performed


Case2:
User enters tes
1 second pass
user presses t
2 seconds pass
search is performed on test

Case3:
User enters tes
1 second passes
user presses t
1.5 seconds pass
user presses i
1.5 seconds pass
user presses n
1.5 seconds pass
user presses g
2 seconds pass
search in performed on testing

so as you can see, the search action is only performed when there has been no key presses(or pastes ect) in the two seconds following a key press.

my basic idea is to.

on keydown Call a function that sets a timeout, the function also sets a variable containing the last entry in the textbox. when the timeout expires it checks the value in the box to see if it matches the value in the variable.

If they match then there has been no change. So do the search

If they dont then do nothing, because the timeout from the subsequent key press will be following to do the same check.

Is this the only/best way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following function from Remy Sharp will do the trick:

function throttle(f, delay){
    var timer = null;
    return function(){
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = window.setTimeout(function(){
            f.apply(context, args);
        },
        delay || 500);
    };
}

In the preceding code, f is the function you would like to throttle and delay is the number of milliseconds to wait after the last call (defaults to 500 if omitted). throttle returns a wrapper function that clears any existing timeouts from previous calls and then sets a timeout for delay milliseconds in the future to call f. A reference to the arguments of the returned function is used to call f with, ensuring f receives the arguments it is expecting.

You should use it as follows:

$('#search').keyup(throttle(function(){
    // do the search if criteria is met
}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...