JSFiddle - React, Tailwind, and code Playground
by gschutz
HTML
<h3>debounce</h3>
<input id="debounce" type="text" placeholder="type to see the delay">
<div>Result:</div>
<div class="debounce result"></div>
<hr>
<h3>throttle</h3>
<input id="throttle" type="text" placeholder="type to see the delay">
<div>Result:</div>
<div class="throttle result"></div>
CSS
.result {
min-height: 50px;
}
JavaScript
function myDebounce(fn, bufferInterval) {
var timeout;
return function () {
var that = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
fn.apply(that, args);
}, bufferInterval);
};
}
function myThrottle(fn, bufferInterval) {
var interval;
return function () {
var that = this, args = arguments;
if (!interval) {
// dispatch fn now, and after interval
fn.apply(that, args);
interval = setInterval(function() {
fn.apply(that, args);
clearInterval(interval);
interval = undefined;
}, bufferInterval);
}
};
}
var debounceInput = document.querySelector('#debounce');
debounceInput.onkeyup = myDebounce(function() {
document.querySelector('.debounce.result').innerText = debounceInput.value;
console.log(this, event);
}, 2000);
var throttleInput = document.querySelector('#throttle');
throttleInput.onkeyup = myThrottle(function() {
document.querySelector('.throttle.result').innerText = throttleInput.value;
console.log(this, event);
}, 2000);