Run function after user has stopped typing
I h开发者_Go百科ave 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
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.
Use the bindWithDelay jQuery plugin:
element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)
I have posted a solution when it ll show user is typing and user stopped type
function typingAction(){
$('#typing').text("user is typing....");
clearTimeout();
setTimeout(()=>{
$('#typing').text(' user stopped typing.....'); //**can call your function here**
},2000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat | ChatApp</title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="/css/styles.css">
</head>
<body >
<p id="typing"></p>
<input name="message" type="text" placeholder="Message" autofocus autocomplete="off" oninput="typingAction()" />
</body>
</html>
精彩评论