Skip to content

Instantly share code, notes, and snippets.

@happymishra
Created July 2, 2019 16:08
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/dd40b4c456fd3b7c9ea3a94b8dbaad99 to your computer and use it in GitHub Desktop.
Save happymishra/dd40b4c456fd3b7c9ea3a94b8dbaad99 to your computer and use it in GitHub Desktop.
<html>
<style>
div {
border: 1px solid black;
width: 300px;
height: 200px;
overflow: scroll;
}
</style>
<body>
<div id="div-body">
<p style="background-color: red; height: 700px">
1. This is line 1
</p>
<p style="background-color: blue; height: 700px">
2. This is line 2
</p>
<p style="background-color: green; height: 700px">
3. This is line 3
</p>
<p style="background-color: yellow; height: 700px">
4. This is line 4
</p>
</div>
<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 divBodyDom = document.getElementById('div-body');
// 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
}
// Throttle function: Input as function which needs to be throttled
// and delay is the time interval in milliseconds
var throttleFunction = function (func, delay) {
// If setTimeout is already scheduled, no need to do anything
if (timerId) {
return
}
// Schedule a setTimeout after delay seconds
timerId = setTimeout(function () {
func()
// Once setTimeout function execution is finished, timerId = undefined
// so that in the next event function execution can be scheduled
timerId = undefined;
}, delay)
}
// Event listener on the input box
divBodyDom.addEventListener('scroll', 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;
// Throttles makeAPICall method such that it is called
// once in every 200 milliseconds
throttleFunction(makeAPICall, 200)
})
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment