Introduction
Limiting how often the function is run is recommended when adding a performant-heavy function to an event listener in JavaScript.
Debouncing and throttling approaches limit the number of times a function can execute. In most cases, the developer decides how many times or when a function will be performed. However, in some circumstances, developers provide consumers with this ability. It is now up to the user to select when and how often that function should be executed.
So, we will see such functions as debounce() and throttle() in this blog.
For example-
Html file
<html>
<body>
<h2>Coding Ninjas</h2>
<label>Search</label>
<!-- Renders an HTML input box -->
<input type="text" id="search-box" />
<p>No of times event fired</p>
<p id='show-api-call-count'></p>
</body>
<script src="issueWithoutDebounceThrottling.js"></script>
</html>
JS file
var searchBoxDom = document.getElementById('search-box');
function makeAPICall() {
// This represents a very heavy metho which takes a lot of time to execute
}
// Add "input" event listener on the text box or search bar
searchBoxDom.addEventListener('input', function() {
var showApiCallCountDom = document.getElementById('show-api-call-count');
var apiCallCount = showApiCallCountDom.innerHTML || 0;
// A very heavy method which takes a lot of time to execute
makeAPICall()
apiCallCount = parseInt(apiCallCount) + 1;
// Updates the number of times makeAPICall method is called
showApiCallCountDom.innerHTML = apiCallCount;
})
Output-
Debounce Method
The debouncing method restricts the time-consuming tasks or functions from firing often. By doing so, it enhances the efficiency of the system. JavaScript provides the debounce() function to achieve debouncing. The debounce() function in JavaScript restricts a function from running again for a certain period of time. The number of times a function can be called is limited due to this.
The debounce() function reduces the program's overhead by preventing the function from being called multiple times.
Let's go through an example to understand debouncing in JavaScript.
<html>
<body>
<button id="debounce">
Button
</button>
<script>
var button = document.getElementById("debounce");
const debounce = (func, delay) => {
let debounceTimer
return function() {
const context = this
const args = arguments
clearTimeout(debounceTimer)
debounceTimer
= setTimeout(() => func.apply(context, args), delay)
}
}
button.addEventListener('click', debounce(function() {
alert("Hello, regardless of how many times you click the debounce button, I'm performed once every 3 seconds!!")
}, 3000));
</script>
</body>
</html>
Output-