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>
CSS
div {
background-color: grey;
color: white;
height: 300px;
padding: 1rem;
width: 25%;
}
div:nth-child(1) { background-color: red; }
div:nth-child(2) { background-color: orange; }
div:nth-child(3) { background-color: yellow; }
div:nth-child(4) { background-color: green; }
div:nth-child(5) { background-color: blue; }
div:nth-child(6) { background-color: purple; }
TypeScript
/**
* Debounce
*
* Prevents a function from being fired too often by determining
* a difference in time from the last time in which it was fired
*
* @author Matt Kenefick <polymermallard.com>
*/
class Debounce
{
/**
* 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;
/**
* @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;
if (diff > this.threshold) {
this.lastTrigger = now;
this.callback();
}
}
}
// Implementation
// --------------------------------------------------------------------------
function myFunction() {
console.log('This is the debounced function');
}
const event = new Debounce(myFunction, 500);
// Test 1: Run via interval at 60FPS
/* setInterval(event, 1000 / 60); */
// Test 2: Run on document scroll
window.addEventListener('scroll', event);