I have an input field in which user can input a long value. This value is then used as input value in a complex time consuming function.
My question is: how can I start execution of this function approximately 1 second after the user finished his typing? (I don't want to run it after each key press as it is really slowing the page). So if his next keystroke is in the 1s limit from the last key stroke, than wait additional second.
Do you have any suggestions?
additional note: I also need to pass some parameters into this function
Solution. To avoid that problem, we better execute a function in proper timing which means after a user stops typing for a while. And setTimeout helps us to do that. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
$('input#username'). keypress(function() { var _this = $(this); // copy of this object for further usage setTimeout(function() { $. post('/ajax/fetch', { type: 'username', value: _this.
One possible way is to attach a keyup event to the input element and send an HTTP request for each character entered to the server to fetch search results: const input = document. querySelector('#input-text'); // Listen for `keyup` event input.
Here's a rough draft : http://jsfiddle.net/jomanlk/msmJp/
Uses setTimeout
and clearTimeout
var timer = null;
$('#text').keyup(function(){
clearTimeout(timer);
timer = setTimeout(doStuff, 1000)
});
function doStuff() {
alert('do stuff');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='text'>
This is really late, I know, but I really disliked the lines of code needed to achieve this every time it was needed, so I extracted the logic into a page initiation function that only runs once.
(function(){
var keystoppedTimer = null;
var keystoppedInputs = document.getElementsByTagName('input');
for (var i = 0, l = keystoppedInputs.length; i < l; i++) {
keystoppedInputs[i].addEventListener('keydown', function(event){
clearTimeout(keystoppedTimer);
keystoppedTimer = setTimeout(function() {
event.target.dispatchEvent( new Event('keystopped') );
}, 600);
}, false);
}
}());
Adding this (think of it as a polyfill), allows for much simpler usage. All you need to do to target the user stopping typing is add an event listener to your element targeting 'keystopped'.
inputElement.addEventListener('keystopped', function(event){
console.log('Stopped typing');
}, false);
I picked keystopped
because it matches keydown
, keyup
, etc.
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