Skip to content

Instantly share code, notes, and snippets.

@happymishra
Created July 2, 2019 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save happymishra/858ed688214957dd3826007241629d89 to your computer and use it in GitHub Desktop.
Save happymishra/858ed688214957dd3826007241629d89 to your computer and use it in GitHub Desktop.
<html>
<body>
<label>Search</label>
<!-- Renders an HTML input box -->
<input type="text" id="search-box">
<p>No of times user actually clicked</p>
<p id='show-api-call-count'></p>
<p>No of times debounce executed the method</p>
<p id="debounc-count"></p>
</body>
<script>
var timerId;
var searchBoxDom = document.getElementById('search-box');
// This represents a very heavy method. Which takes a lot of time to
// execute
function makeAPICall() {
var debounceDom = document.getElementById('debounc-count');
var debounceCount = debounceDom.innerHTML || 0;
debounceDom.innerHTML = parseInt(debounceCount) + 1
}
// Debounce function: Input as function which needs to be debounced
// and delay is the debounced time in milliseconds
var debounceFunction = function (func, delay) {
// Cancels the setTimeout method execution
clearTimeout(timerId)
// Executes the func after delay time.
timerId = setTimeout(func, delay)
}
// Event listener on the input box
searchBoxDom.addEventListener('input', function () {
var apiCallCountDom = document.getElementById('show-api-call-count');
var apiCallCount = apiCallCountDom.innerHTML || 0;
apiCallCount = parseInt(apiCallCount) + 1;
// Updates the number of times makeAPICall method is called
apiCallCountDom.innerHTML = apiCallCount;
// Debounces makeAPICall method
debounceFunction(makeAPICall, 200)
})
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment