0

I have this part of code:

$('#clientsfilter').on('input', function() {
     var string = $('#clientsfilter').val();
     if (string != "") {
         //console.log("input is not empty");
         var timeoutid = setTimeout(function() {
             // some stuff
             console.log("fired!");   
         }, 1500);
         console.log("timeoutid is "+timeoutid);
     }
     else
     {
        // console.log("input is empty");
     }    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="clientsfilter" type="text" size="27">

When a user types something, it perform some actions after 1,5 seconds. But if a user will type one symbol after another too fass (time between symbols less than 1,5 seconds), the setTimeout() stuff will fire every time user adds symbol (or deletes). I want to prevent firing setTimeout function too many times, only if 1.5 seconds passed from last typing. I found information about

clearTimeout(timeoutid);

But how can I use it my situation?

R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77
Antony Slahin
  • 31
  • 1
  • 5
  • 1
    You're looking for a debounce or throttle function. – AKX Feb 08 '22 at 12:57
  • What is "too many times"? – Esszed Feb 08 '22 at 12:57
  • @Esszed — The question does explain that. *"the setTimeout() stuff will fire every time user adds symbol (or deletes)."* is what happens. *"I want to prevent firing setTimeout function too many times"* describes the former situation. *"only if 1.5 seconds passed **from last typing**"* is what is desired – Quentin Feb 08 '22 at 12:59
  • @Quentin Got it! Thanks. – Esszed Feb 08 '22 at 13:13
  • So, i found the solution. Thanks guys for telling about debounce. Now the code is like this: `function debounce( callback, delay ) { let timeout; return function() { clearTimeout( timeout ); timeout = setTimeout( callback, delay ); } } function filterClients() { var string = $('#clientsfilter').val(); if (string != "") { // stuff } else { } } const clientsfilter = document.getElementById("clientsfilter"); clientsfilter.addEventListener( "keyup", debounce( filterClients, 1500 ) );` – Antony Slahin Feb 08 '22 at 13:54

0 Answers0