JSFiddle - React, Tailwind, and code Playground
by ischenkodv
HTML
<script src="https://unpkg.com/handle-events/dist/handle-events.min.js"></script>
<form action="throttle" onsubmit="return false;">
<input type="text" id="address" placeholder="type to see the throttle" />
<div id="label">Start typing...</div>
<div id="history"></div>
</form>
CSS
form {
width: 50%;
}
form input[type="text"] {
width: 100%;
margin: 5px 2px;
padding: 2px 5px;
box-sizing: border-box;
line-height: 22px;
font-size: 14px;
}
#label {
margin: 7px 2px;
color: orangered;
font-style: italic;
}
#history {
width: 100%;
margin: 7px 2px;
padding: 3px 5px;
box-sizing: border-box;
border: solid 1px #aaa;
}
JavaScript
init();
/**
* Throttle the execution of a function in the specified time.
*
* @param {Function} listener - the event handler to call upon the event triggered
* @param {Number} delay - the number of milliseconds to throttle the listener
* @return {Function}
*/
function throttle(listener, delay) {
let timer = null;
const cbTimeout = () => {
clearTimeout(timer);
timer = null;
write('#label', 'Ready!'); // remove, for test
};
return function throttledListener(evt) {
const contex = this;
if (timer != null) {
evt.stopImmediatePropagation();
write('#label', 'Busy...'); // remove, for test
return;
}
timer = setTimeout(cbTimeout, delay);
listener.call(contex, evt);
};
}
/**
* This keyCodes correspond to a key on the keyboard, including codes for special keys.
* This codes work with the `keydown` event.
*
* @see
* https://api.jquery.com/keydown/#example-0
* https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
*/
const NOT_PRINTABLE_KEYS = {
backspace: 8,
tab: 9,
enter: 13,
shift: 16,
ctrl: 17,
alt: 18,
pause: 19,
capsLock: 20,
esc: 27,
pageUp: 33,
pageDown: 34,
end: 35,
home: 36,
leftArrow: 37,
upArrow: 38,
rightArrow: 39,
downArrow: 40,
insert: 45,
delete: 46,
f1: 112,
f2: 113,
f3: 114,
f4: 115,
f5: 116,
f6: 117,
f7: 118,
f8: 119,
f9: 120,
f10: 121,
f11: 122,
f12: 123,
numLock: 144,
scrollLock: 145,
};
/**
* Determines whether the key pressed is not printable (in `keydown` event)
*
* @param {Number} keyCode - the key pressed
* @return {Boolean}
*/
function isNotPrintableKey(keyCode) {
for (var char in NOT_PRINTABLE_KEYS) {
if (NOT_PRINTABLE_KEYS[char] === keyCode) return true;
}
return false;
}
/**
* Event handler for the `keydown` event when typing an address.
*
* @param {Event} evt - the event triggered
* @return {void}
*/
function onKeydown(evt) {
const key = evt.charCode ||...