Call function when user stops writing input field – Javascript

In this article, we are going to show you a technique that helps you call a function when the user stops writing in an input field, using Javascript. Suppose you have an input field for search and you want to show search suggestions to the user as he types. So typically you do the following:

<!-- input field -->
<input id="input" />

<script>

	// function to be called whenever input field text value is changed
	function onInput() {
		// get the input field DOM in a separate variable
		const self = this

		// write your logic here to get suggestions
		console.log(self.value)
	}

	// attach an event listener to input field that will be called whenever its text changed
	document.getElementById("input").addEventListener("input", onInput)
</script>

The problem with this method is, if you are calling an AJAX request inside onInput() function, then it will call an HTTP request on each input change. So if the user types 5 characters in 1 second, it calls 5 AJAX requests in 1 second. But you should only call the AJAX request once.

So we will be using a technique called debounce. Change your onInput() function to the following:

// timer object
let timer;

// function to be called whenever input field text value is changed
function onInput() {
	// get the input field DOM in a separate variable
	const self = this
	
	// if user types another key before 500 milliseconds,
	// then remove the timer, so the function will not gets called
	clearTimeout(timer)

	// this will create a timer every time input field has a value
	timer = setTimeout(function () {
		// write your own logic when user stops typing
		console.log(self.value)
	}, 500)
}

You can see that we have created a global variable timer. Comments have been added with each line for an explanation. Now your AJAX request will only be called when the user stops writing.

You can also check our auto-search suggestion tutorial for a real-world example.

6 Replies to “Call function when user stops writing input field – Javascript”

  1. An intriguing discussion is definitely worth comment. I believe that
    you should publish more about this topic, it might not be a taboo subject but
    generally folks don’t speak about these subjects. To the next!
    Many thanks!!

  2. Hi would you mind stating which blog platform you’re using?
    I’m looking to start my own blog soon but I’m having a hard
    time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique.
    P.S My apologies for being off-topic but I had to ask!

  3. Hi everybody, here every person is sharing these know-how, so it’s pleasant to read this
    webpage, and I used to go to see this weblog all
    the time.

Comments are closed.