0

I need to create a search box which starts searching only 3 seconds after the user stops typing. I have seen so many ways to do that using Reactjs, like this post. The problem is that I have to do that in native JS (without any libraries or frameworks) and HTML.

1 Answers1

0

you have to play with keydown and keyup.

when keydown, you initiate an interval and reset the waiting timing.

when keyup, you set the interval function. This function test the 3 seconds, and reset the interval and the event listener.

let wait3s = 0;
let timing = 3000;
let myInt;

const searchKeydown = (evt) => {
  //console.log(evt.keyCode);
  wait3s = 0;
  clearInterval(myInt);
};
document.querySelector('#mySearch').addEventListener('keydown', searchKeydown);

const searchKeyUp = (evt) => {
  //console.log(evt.keyCode);
  setSearchInterval();
};
document.querySelector('#mySearch').addEventListener('keyup', searchKeyUp);

const setSearchInterval = () => {
  myInt = setInterval(function() {
    if (wait3s >= timing) {
      console.log('3 seconds');
      clearInterval(myInt);
      document.querySelector('#mySearch').removeEventListener('keyup', searchKeyUp)
    } else {
      wait3s += 100;
    }
  }, 100);
};
<div class="container">
  <label for="mySearch">Search:</label>
  <input type="search" id="mySearch">
</div>

I put variables and left the in comment evt.keycode, for you to play and test it

pier farrugia
  • 1,520
  • 2
  • 2
  • 9