Lee Lee - 25 days ago 7
jQuery Question

jQuery - Search on text entry - delay until full term entered

I have the following code, which detects any text entered into the search-box field and then immediately runs the search (if greater than 2 characters):

$('#search-box').on('input', function() {

var term = $(this).val();
if (term.length > 2) {
//execute search and display results
}

});


This doesn't look pretty though, as if you were to type "dollar" for example, after "doll" a load of dolls will appear, which will then be replaced with dollars once "dolla" is entered. This can happen in a split second.

What I'd like to do is determine whether the user has finished the search term. Is it possible to wait for a second or 2 before doing the search? And if in that waiting period the user enters another letter, it resets the clock?

Answer

You will have to use setTimeout() for waiting after input.

var tim = '';
$('#search-box').on('input', function() { 
    clearTimeout(tim);
    tim = setTimeout(my_func, 2000); //2000 means 2 seconds; 
});

function my_func() {
    var term = $(this).val();
    if (term.length > 2) {
        //execute search and display results
    }
}

Seconds are in ms and hence you can also set something like 1500 for one and half second.

clearTimeout is used for destroying values in tim. After clearTimeout(tim), tim becomes zero and then starts after increase/decrease in length of #search-box.

Comments