Summary: in this tutorial, you’ll learn about the JavaScript debounce function and how to use it to improve application performance.
To understand the debounce function, we’ll build a Wikipedia Search application using the debouncing programming technique.
Create the project folder structure
First, create a new folder called wikipedia-search that will store the files of the projects.
Second, create three folders inside the wikipedia-search folder called js, css, and img. These folders will store JavaScript, CSS, and image files accordingly.
Third, create the style.css in the css folder and the app.js in the js Also, download the following image and copy it to the img folder. You’ll use the logo to make the UI for the app.
Finally, create an index.html file in the root folder.
The project structure will look like the following:
Build the HTML page
Open the index.html file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wikipedia Search</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>
<img src="./img/wikipedia-logo.png" alt="wikipedia">
<h1>Wikipedia Search</h1>
<input type="text" name="searchTerm" id="searchTerm" placeholder="Enter a search term...">
</header>
<main id="searchResult"></main>
<script src="js/app.js"></script>
</body>
</html>Code language: HTML, XML (xml)In this HTML file:
- First, link to the
style.cssfile in the<head>section. - Second, add a
<script>tag whosesrclinks to theapp.jsfile and place it right before the</body>tag. - Third, add two sections to the body of the HTML page. The first section is the header which shows the Wikipedia logo, the heading, and the search box. The second section includes the
<main>tag that will display the search result.
Copy the CSS code
Please navigate to the style.css file, copy its code, and paste it into the style.css file in the css folder. When you open the index.html file, you should see something like the following page.
Handle input events
First, select the <input> and search result elements using the querySelector() method:
const searchTermElem = document.querySelector('#searchTerm');
const searchResultElem = document.querySelector('#searchResult');Code language: JavaScript (javascript)Second, set the focus on the <input> element by calling the focus() method:
searchTermElem.focus();Code language: JavaScript (javascript)Third, attach an input event listener for the <input> element:
searchTermElem.addEventListener('input', function (event) {
console.log(event.target.value);
});Code language: JavaScript (javascript)If you type some text on the <input> element, you’ll see that the input event occurs, which shows the text to the Console.
For example, when you type the debounce in the <input> element: