You need to implement this behavior so that when a new letter is entered in a field, 1 second will pass and a certain method will be executed. A timer is needed for this, but when letters are quickly entered (for example, 3 letters per second), the timers are queued and then executed sequentially.

It is required that there should be a timer that, with each new letter entered, will be restarted, but if the letters were not entered within 1 second. then the desired method was run.

Here is my code:

var isTimerWork = false; var timer = null; $('#SearchString').on("keyup", function() { if ($('#SearchString').val().length >= 2 && !IsExtSearch) { if (timer != null) clearTimeout(timer); timer = setTimeout(isTimerWork = true, 1000); while (!isTimerWork); GetAutoCompleteData($('#SearchString').val()); } 

in my case, it turns out that a new timer is created every time.

  • in your case, you could hang endlessly in a while loop (!isTimerWork); if I didn’t immediately assign true to this variable before it - Grundy

1 answer 1

Use the setInterval function more correctly,

 setTimeout(function() { //тут код, который выполнится через 1 секунду }, 1000); 

Corrected your example:

 var timer = null; $('#SearchString').on("keyup", function() { clearTimeout(timer); if ($('#SearchString').val().length >= 2) { timer = setTimeout(function() { console.log($('#SearchString').val()); }, 1000); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input id="SearchString" type="text" name="test" value="a" /> 

  • you can not check for null. And once clearTimeout is called in both branches, you can make this call out of the condition - Grundy
  • @Grundy Thank you, corrected - MrFylypenko
  • one
    if you can also remove and immediately call clearTimeout - Grundy