I'm making a list filter and want a delay in case the user is a fast typer. Looking at different solutions for similar questions hasn't helped me and I don't understand the logic they implement.
This is my current code:
$.fn.filterList = function(){
var inputFilter = $(this);
var list = $('#' + inputFilter.data('list'));
var listItems = list.children('li');
inputFilter.keyup(function(){
setTimeout(function () {
var term = inputFilter.val().toLowerCase();
listItems.each(function(i, e){
var city = ($(e).text()).toLowerCase();
if(city.startsWith(term)){
console.log(city);
}
});
}, 800);
});
};
$('.my-input').filterList();
The problem with this is that it will trigger on each keyup, no matter how fast the user types.
How can I implement a delay so that it does not trigger for each keyup?
On each successive keypress you need to clear the previous timer so that the function only fires X milliseconds after typing ends. Try this:
var timer;
inputFilter.keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
var term = inputFilter.val().toLowerCase();
listItems.each(function(i, e) {
var city = $(e).text().toLowerCase();
if (city.startsWith(term)) {
console.log(city);
}
});
}, 800);
});
Here's a simplified working example:
var timer;
$('#foo').keypress(function() {
clearTimeout(timer);
timer = setTimeout(function() {
$('div').fadeIn('fast').delay(1000).fadeOut('fast');
}, 800);
});
div { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="foo" />
<div>You stopped typing 1 second ago</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With