Working with Timers
Learn to use timers to display search results after the last key is pressed.
Using timers
When someone opens the search panel and starts typing, we want to respond to them but we don’t want to send a search query to the database after every key press. Instead, it is better to wait for the typing to pause and then query the database. When a user starts typing, we can set a timer. The timer is reset if the user types another letter before it finishes. When the timer is finally up, the search request is sent to the database.
With the Excellence folder open in VS Code, open the terminal by clicking the "View" option and choosing "Terminal." Run the start script using the
npm run start
command. The start script will watch for any changes in the code and recompile it.
Inside the theme folder, open the src folder. Open the modules folder and then open Search.js
.
In the previous lesson, we created a property for the input element in the constructor called searchInput
.
constructor(){//...this.searchInput = document.querySelector("#search-query");//...}
When the user types a search query in the input box, we will create an event to respond to it. We can attach an event listener to searchInput
to look for a keydown
or keyup
event. When the user types something in the search box, the callback function handleSearchQuery
will be called.
events(){this.searchIcon.addEventListener("click", this.openSearchPanel.bind(this));this.cancelIcon.addEventListener("click", this.closeSearchPanel.bind(this));document.addEventListener("keyup", this.keyPressed.bind(this));this.searchInput.addEventListener("keyup", this.handleSearchQuery.bind(this));}
Since the addEventListener
method changes the value of the keyword this
to point to the element which triggered it, we need to use .bind(this)
afterwards to make sure this points to the global object.
In the handleSearchQuery
method, we will display a message on the console when the user types something in the search box.
To check the message on the console, we can right click the page and click the "Inspect" option. From the panel that opens up, choose the "Console" option.
handleSearchQuery(){console.log("A key was pressed!")}
Back in the browser, when the user opens the search panel and types a search query, the above ...