How to add a wait timer for an input keyup event?

I have an input field and it has a keyup event:

$(document).ready(function() { $('#SearchInputBox').keyup(function() { DoSearch($(this).val()); }); }); 

How to add a delay time, so that only when the user stops printing for 1 second, then he will launch the DoSearch function. I do not want to run it every time the user enters a key, because if they are quickly typed, then he will be behind.

+6
source share
1 answer

Basically, set a timeout for each keyboard. If you already have a timeout, clear it and set another. The DoSearch() function is only launched when the timeout is allowed to complete without being reset with another key (that is, when the user stopped typing in 1000 ms).

 var timeout = null; $('#SearchInputBox').on('keyup', function () { var that = this; if (timeout !== null) { clearTimeout(timeout); } timeout = setTimeout(function () { DoSearch($(that).val()); }, 1000); }); 
+13
source

Source: https://habr.com/ru/post/946978/


All Articles