Run function after user has stopped typing
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.
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'>
Use the bindWithDelay jQuery plugin:
element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)