JSFiddle - React, Tailwind, and code Playground
by ktstowell
HTML
<div id="form" class="column">
<h1>Debouncer!</h1>
<label for="">Data:</label>
<input type="text" name="data" placeholder="Type here!"/>
</div>
<div id="demo"class="column">
<p>Times: updated: <span>0</span></p>
</div>
JavaScript
// Let’s create a namespace for our time related functions.
var Timer = {};
// Debounce Interval, in ms. It’s a good idea to make something like this “implementer configurable”. This is the equivalent of “putting a minute on the clock".
Timer.debounceInterval = 100;
// Time value that gets manipulated
Timer.currentTime;
// Store the setInterval function
Timer.interval;
// Create a pointer to a function that gets called when the timer runs out.
// Be sure to only point to a reference, and not () an execution.
Timer.onTimeout = update;
// This is the equivalent of running the clock and would be the callback of your registered event handler.
// The 'data' argument more or less represents an event object from the aforementioned handler.
Timer.run = function(data) {
var self = this;
// Set/reset time.
this.currentTime = this.debounceInterval;
// Prevent the current interval from running out - this isn’t technically necessary with the current code, but it helps me feel like I’m covering a potential gap.
clearInterval(self.interval);
// Create a new one.
// We use setInterval here to get as close to a 1ms representation as possible.
this.interval = setInterval(function() {
// Decrement time
self.currentTime--;
// Check for timeout. Since zero is falsy we can get away with just doing this:
if(!self.currentTime) {
// Run the callback
self.onTimeout(data);
// If it timesout, clear the interval
clearInterval(self.interval);
}
}, 1);
};
// Updater visualizer
var tracker = document.querySelector('span');
// Times triggered.
var times_updated = 0;
// The timeout callback
function update(data) {
times_updated++;
tracker.textContent = times_updated;
};
// Input field that will trigger the tracking
var field = document.querySelector('input');
// Register event listener.
field.addEventListener('keyup', function(e) {
...