Throttled search

by Kumar Sidharth

HTML

<label for="search">Throttled Search</label>
<input value=""
      type="search"
      placeholder="search"
      data-throttle-keyup
      data-throttle-time="550"
      id="search"
      spellcheck="true"/>

CSS

body {
  background: black;
  font-family: helvetica;
}
label {
  display: block;
  color: lightgrey;
}
input[type=search] {
  background: darkgrey;
  padding: 10px;
  border-radius: 20px;
}

TypeScript

function getData(inputValue: string): void {
  console.log(inputValue);
}

const throttledKeupEventName = 'throttledKeyup';

document.querySelector('[data-throttle-keyup]')
				.addEventListener(throttledKeupEventName, ({detail: {currentValue}}) => {
	getData(currentValue);
});

// throttle logic

function createThrottleKeyupEvent(keyupEvent: KeyupEvent, inputElement: HTMLInputElement): CustomEvent {
	const detail = {
    keyupEvent,
    currentValue: inputElement.value,
  };
  return new CustomEvent(throttledKeupEventName, {
  	detail,
    bubbles: false,
  });
}


const addThrottleEventInput = () => {
  	const input = document.querySelector('[data-throttle-keyup]');
    const throttleTime = input.getAttribute('data-throttle-time');
    let timeout = null;

    function throttle(event, timeOutTime) {
      if (timeout) {
        return;
      }

      timeout = setTimeout(() => {
        const throttledEvent = createThrottleKeyupEvent(event, input);
        input.dispatchEvent(throttledEvent);
        timeout = null;
      }, timeOutTime);
    }

    input.addEventListener('keyup', (event) => 
    																			throttle(event, throttleTime));
 };
 
 addThrottleEventInput();