JSFiddle - React, Tailwind, and code Playground
HTML
<div>Scroll me.</div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
CSS
div {
background-color: grey;
color: white;
height: 300px;
padding: 1rem;
width: 25%;
}
div:nth-child(6n + 1) { background-color: red; }
div:nth-child(6n + 2) { background-color: orange; }
div:nth-child(6n + 3) { background-color: yellow; }
div:nth-child(6n + 4) { background-color: green; }
div:nth-child(6n + 5) { background-color: blue; }
div:nth-child(6n + 6) { background-color: purple; }
TypeScript
/**
* InclusiveDebounce
*
* Prevents a function from being fired too often by determining
* a difference in time from the last time in which it was fired.
*
* Applies inclusive techniques to execute functions one last time.
*
* @author Matt Kenefick <polymermallard.com>
*/
class InclusiveDebounce
{
/**
* Debounced function
*
* @type function
*/
public callback: () => void;
/**
* Time in between triggers
*
* @type number
*/
public threshold: number;
/**
* Last time this function was triggered
*
* @type number
*/
private lastTrigger: number = 0;
/**
* Timeout for calling future events
*
* @type number
*/
private timeout: number = 0;
/**
* @param function callback
* @param number threshold
* @return function
*/
public constructor(callback: () => void, threshold: number = 200): () => void {
this.callback = callback;
this.threshold = threshold;
return this.run.bind(this);
}
/**
* Executable function
*
* @return void
*/
public run(): void {
const now: number = Date.now();
const diff: number = now - this.lastTrigger;
// Execute Immediately
if (diff > this.threshold) {
this.lastTrigger = now;
this.callback();
}
// Cancel future event, if exists
if (this.timeout !== 0) {
clearTimeout(this.timeout);
this.timeout = 0;
}
// Create future event
this.timeout = setTimeout(this.callback, this.threshold);
}
}
// Implementation
// --------------------------------------------------------------------------
function myFunction() {
console.log('This is an inclusive debounced function');
}
const event = new InclusiveDebounce(myFunction, 1500);
// Test 1: Run on document scroll
window.addEventListener('scroll', event);