JSFiddle - React, Tailwind, and code Playground

by dpnminh

HTML

<input type="text" class="js-search" id="search1">
<div id="result">

</div>

JavaScript

/*
If you were building a search tool and wanted search results to pop up as you 
typed but the server call was taxing, write a function that gets called on every 
key down but calls the server when the user stops typing for 400ms. 
*/

// <input type="text" class="js-search">
/*
Questions to ask: 
1. Each of input should have unique id, where is the id in this case?
2. Where to display search results?
3. How many search input there will be in one page?
4. URL Query request format?
5. What about error in request response?
6. What is the format of result? String? JSON?
*/

(function(){
  var searchTool = {
    timer: 400,
    query: (str) => {
      let params = new URLSearchParams(`q=${str}`).toString();
            
      /* fetch(`http://localhost:3000/?${params}`)
      .then((result) => {
        document.getElementById('search-result').innerHTML = result;
      })
      .catch((err) => console.log(err)) */
      
      console.log(params);
    },
    bindToSearchBoxes: function(ids){
      var inputs = document.querySelectorAll(`input#${ids}`);
      
      var onKeyDown = (() =>{
        var lastRequest;
        
        return (e) => {
          if (lastRequest){
            clearTimeout(lastRequest);
          }
          
          lastRequest = setTimeout(()=>{
            searchTool.query(e.target.value);
          }, searchTool.timer);
        }
      })();
      
      for(var i = 0; i < inputs.length; i++){
        inputs[i].addEventListener('keydown', onKeyDown);
      }   
    }
  };
  
  searchTool.bindToSearchBoxes('search1');
})();