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" oninput="onInput()" />

<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 = event.target

		// write your logic here to get suggestions
		console.log(self.value)
	}
</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 = event.target
	
	// 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.