Instant search function in Javascript

2020-03-30 03:14发布

I am using the following javascript for my instant search function (to detect when the visitor stops writing, so the function won't run on every single keyup).

It works but it’s more delay than 1000 milliseconds. Even if I set it to 200 milliseconds it’s 1-2 seconds delay before the instant search function runs.

Is there a better/faster way to detect when the visitor has stopped typing in the input (I only need it for Internet Explorer if that’s make any difference).

$(document).ready(function(){

var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();

$('input').keyup(function() {
delay(function(){
//instant search function here
}, 1000 );
});

});

New idea: When I think about it the problem is that I can’t continue writing in the input filed when the function runs. Any solution for that and I will not be needing any delay function.

3条回答
We Are One
2楼-- · 2020-03-30 03:35
function instantSearch(){ ... }

var timer;
$('input').keyup(function(){
   timer && clearTimeout(timer);
   timer = setTimeout(instantSearch, 200);
});
查看更多
仙女界的扛把子
3楼-- · 2020-03-30 03:55

Is your instant search function making an AJAX request to return results? That might be the difference between setting the delay to 200ms and getting your response back 1-2s later.

查看更多
\"骚年 ilove
4楼-- · 2020-03-30 03:57

If you're using the keyup event it shouldn't be necessary to specify a delay unless there are specific limits on queries-per-second or something similar.

There's a fairly concise walkthrough here: http://blog.comperiosearch.com/2012/06/make-an-instant-search-application-using-json-ajax-and-jquery/

查看更多
登录 后发表回答