How to delay the .keyup() handler until the user stops typing?
I use this small function for the same purpose, executing a function after the user has stopped typing for a specified amount of time or in events that fire at a high rate, like resize
:
function delay(callback, ms) {
var timer = 0;
return function() {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
// Example usage:
$('#input').keyup(delay(function (e) {
console.log('Time elapsed!', this.value);
}, 500));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="input">Try it:
<input id="input" type="text" placeholder="Type something here..."/>
</label>
Run javascript function when user finishes typing instead of on key up?
So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, let's start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.
Making a few assumptions...
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 seconds for example
var $input = $('#myInput');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
//do something
}
jQuery keyup with delay
let delay = (()=>{
let timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
window.document.getElementById("myInputingNumber").addEventListener("keyup",function() {
delay(function(){
alert('Key Up');
}, 2000 );
});
<input type="text" id="myInputingNumber">
Wait for function till user stops typing
timer = 0;
function mySearch (){
var xx = $(input).val();
doSearch(xx);
}
$(input).live('keyup', function(e){
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(mySearch, 400);
});
it's better to move your function to a named function and call it multiple times, 'cause otherwise you're creating another lambda function on each keyup which is unnecessary and relatively expensive
How to delay @keyup handler in Vue.js
You drop this.timer
value before clearing the interval. Do this instead:
searchTimeOut() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
// your code
}, 800);
}
How to start search only when user stops typing?
You can use setTimeout
with respect to your code as follows,
state = {
name: '',
typing: false,
typingTimeout: 0
}
changeName = (event) => {
const self = this;
if (self.state.typingTimeout) {
clearTimeout(self.state.typingTimeout);
}
self.setState({
name: event.target.value,
typing: false,
typingTimeout: setTimeout(function () {
self.sendToParent(self.state.name);
}, 5000)
});
}
Also, you need to bind changeName
handler function in constructor.
constructor(props) {
super(props);
this.changeName = this.changeName.bind(this);
}
Adding a delay before keyup() fires in jQuery
Put your code in a timeout. Then on subsequent 1keyup
events, clear the timeout and reset it.
That is what this one is doing How to delay the .keyup() handler until the user stops typing?
How to prevent keyup function from lagging when the user types
Solution
I have face similar issue before, I think you might want to try adding something called "debounce", which basically add a delay before doing any process. In the keyup
case, it will wait for the user to stop typing for any set amount of time (let's say 0.5 second) and then do the process (searches or whatever) If you don't use debounce, it will do the search every single time the user trigger the keyup
event.
You can search for articles on how to do debounce, I think there's a lot of them. But in essence it uses the setTimeout
and clearTimeout
function of JS
Here's from the first article I found: https://levelup.gitconnected.com/debounce-in-javascript-improve-your-applications-performance-5b01855e086
const debounce = (func, wait) => {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
How to use this function? simple, just add your actual function (the search function) as the first parameter, and the delay (microseconds) in the second parameter, and then use the .call() function (why do this? because the debounce will return a function). So I guess something like this:
$('input').on('keyup', function(){
var searchTerm = $("input").val().toLowerCase();
debounce(function(){
$('.item').each(function(){
if ($(this).filter('[data-text *= ' + searchTerm + ']').length > 0 || searchTerm.length < 1) {
$(this).parent().show();
} else {
$(this).parent().hide();
}
});
}, 500).call();
});
This is how I will do it, because then I can add some stuff outside of the debounce into the keyup event, but you can just put the debounce returned function into a variable and then bind it with the keyup (like in the article), or just straight up put the debounce inside the keyup, like this:
$('input').on('keyup', debounce(function(){
...
},500));
How does it works?
You can read them in the articles, or find answer in StackOverflow, here's what I got Can someone explain the "debounce" function in Javascript
But if I'm using my own words, basically what you first need to understand is setTimeout
set a timer before a function is called, and clearTimeout
cancel that timer. Now in the debounce you can see that there's a clearTimeout
before any setTimeout
. So every time the keyup event is triggered it will basically cancel the last timeout set (if any), and then it will set a new timeout. In essence, it will reset the timer to what you set every time the event is triggered.
So for example:
- The user want to search "abc"
- They type "a" -> the debounce set a timer of 500ms before calling the
actual search of "a" - Before the 500ms is up, the user type "b", so the debounce cancel that "a" search, and search for "ab" instead, while also setting a timer of 500ms before doing it
- Before the 500ms is up, the user type "c", so cancel the "ab" search, add a timer of 500ms to search for "abc"
- The user stop typing until 500ms is up, now the debounce actually call the search for "abc"
What this results to? The heavy processing for the search is only done once for "abc", you can also put a loader or something to this heavy processing so it looks better for the user
Delay execution of a setTimeout() function until user stops typing
You can use a isTyping
variable to check whether any key is pressed, with setInterval
to wait for isTyping
to become false
. When isTyping
is false, run your function.
Something like this:
You can test by typing in the input fields. When you long press a key, the execution will stop and resume immediately when you release the key.
var isTyping = false;
var interval = null;
var count = 0; // demo only
$('body').on('keyup', ':input', function(e) {
isTyping = false;
});
$('body').on('keydown', ':input', function(e) {
isTyping = true;
});
runTimer();
function executeFunction(){
console.log('Execute', count++);
runTimer();
}
function runTimer(){
// I change to 1 second for easy testing
setTimeout(runExecute, 1 * 1000);
}
function runExecute(){
/**
* If not typing
* clear interval
* execute function
* else, if interval is not set
* set interval
* else
* do nothing, wait for user stop typing
*/
if (isTyping !== true){
clearInterval(interval);
interval = null;
executeFunction();
} else if (!interval){
interval = setInterval(runExecute, 4);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input>
Related Topics
How to Execute a JavaScript Function When I Have Its Name as a String
Client on Node.Js: Uncaught Referenceerror: Require Is Not Defined
Share Data Between Angularjs Controllers
Creating a Blob from a Base64 String in JavaScript
JavaScript Object: Access Variable Property by Name as String
When Is JavaScript'S Eval() Not Evil
How to Use Multiple Versions of Jquery on the Same Page
How to Access Object Properties Containing Special Characters
Does JavaScript Pass by Reference
Can a Website Detect When You Are Using Selenium With Chromedriver
Looping Through Array and Removing Items, Without Breaking For Loop
Accessing the Web Page'S Http Headers in JavaScript
Is It Bad Practice to Have a Constructor Function Return a Promise
Location of Parenthesis For Auto-Executing Anonymous JavaScript Functions