javascript - How do I implement a delay on jQuery keyup? -
i'm making list filter , want delay in case user fast typer. looking @ different solutions similar questions hasn't helped me , don't understand logic implement.
this 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 trigger on each keyup, no matter how fast user types.
how can implement delay not trigger each keyup
?
on each successive keypress
need clear previous timer function 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); });
Comments
Post a Comment