Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Fire a JavaScript function when a user finishes typing instead of on key up?
To fire a JavaScript function when the user finishes typing instead of on every keystroke, use a debouncing technique with setTimeout and clearTimeout. This prevents the function from executing until the user stops typing for a specified delay.
The Problem
Using keyup or input events directly fires a function on every keystroke, which can cause performance issues or unwanted API calls. Debouncing ensures the function only runs after the user has finished typing.
Example with jQuery
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="myText" placeholder="Type something..." />
<p id="output"></p>
<script>
var timer = null;
$("#myText").on('input', function(){
clearTimeout(timer);
timer = setTimeout(function() {
var text = $("#myText").val();
$("#output").text("You typed: " + text);
}, 1000);
});
</script>
</body>
</html>
Vanilla JavaScript Approach
<html>
<body>
<input type="text" id="myText" placeholder="Type something..." />
<p id="output"></p>
<script>
let timer = null;
const input = document.getElementById('myText');
const output = document.getElementById('output');
input.addEventListener('input', function() {
clearTimeout(timer);
timer = setTimeout(function() {
output.textContent = "You finished typing: " + input.value;
}, 1000);
});
</script>
</body>
</html>
How It Works
The debouncing technique works by:
- Setting a timer when the user types
- Clearing the previous timer on each keystroke
- Only executing the function when the timer completes (user stopped typing)
Reusable Debounce Function
<html>
<body>
<input type="text" id="searchBox" placeholder="Search..." />
<div id="results"></div>
<script>
function debounce(func, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
function performSearch(event) {
const query = event.target.value;
document.getElementById('results').innerHTML =
query ? `Searching for: "${query}"` : '';
}
const debouncedSearch = debounce(performSearch, 500);
document.getElementById('searchBox').addEventListener('input', debouncedSearch);
</script>
</body>
</html>
Key Points
- Use
inputevent instead ofkeydownto catch all text changes - Adjust the delay (1000ms = 1 second) based on your needs
- Always clear the previous timeout to reset the timer
- Consider creating a reusable debounce function for multiple inputs
Conclusion
Debouncing with setTimeout and clearTimeout efficiently delays function execution until users finish typing. This technique improves performance and user experience in search boxes, form validation, and API calls.
