From 742aa5fe611de747310f67af4908405307c05612 Mon Sep 17 00:00:00 2001 From: vyanky1227 <132478275+vyanky1227@users.noreply.github.com> Date: Wed, 15 May 2024 14:48:46 +0530 Subject: [PATCH] script.js (song tracker) improvement in code in efficiency Made changes raised by issue #169 --- Song Tracker/scripts/script.js | 49 ++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/Song Tracker/scripts/script.js b/Song Tracker/scripts/script.js index d8ca2116..2cde19f6 100644 --- a/Song Tracker/scripts/script.js +++ b/Song Tracker/scripts/script.js @@ -1,16 +1,26 @@ let term = ''; let previousTerm = ''; +let debounceTimer; const updateTerm = () => { - term = document.getElementById('searchTerm').value.trim(); + const searchTerm = document.getElementById('searchTerm').value.trim(); // Avoid unnecessary API calls if the search term remains the same - if (!term || term === '' || term === previousTerm) { + if (!searchTerm || searchTerm === '' || searchTerm === previousTerm) { return; } - previousTerm = term; + previousTerm = searchTerm; + term = searchTerm; + // Debounce input to avoid frequent API calls + clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => { + fetchData(term); + }, 300); // Adjust debounce delay as needed +}; + +const fetchData = (term) => { const url = `https://itunes.apple.com/search?term=${term}`; //API const songContainer = document.getElementById('songs'); songContainer.innerHTML = ''; // Clear previous search results @@ -21,19 +31,7 @@ const updateTerm = () => { fetch(url) .then((Response) => Response.json()) .then((data) => { - const artists = data.results; - - // Check if there are no results - if (artists.length === 0) { - songContainer.innerHTML = '

No results found.

'; - return; - } - - // Create HTML elements and populate them with data - artists.forEach(result => { - const article = createSongElement(result); - songContainer.appendChild(article); - }); + displayResults(data.results, songContainer); }) .catch(error => { // Display error message @@ -42,6 +40,23 @@ const updateTerm = () => { }); }; +const displayResults = (results, container) => { + if (results.length === 0) { + container.innerHTML = '

No results found.

'; + return; + } + + const fragment = document.createDocumentFragment(); + + results.forEach(result => { + const article = createSongElement(result); + fragment.appendChild(article); + }); + + container.innerHTML = ''; + container.appendChild(fragment); +}; + const createSongElement = (result) => { const article = document.createElement('article'); article.classList.add('song-item'); @@ -82,4 +97,4 @@ const togglePlay = (audioUrl) => { // Initialize search button event listener const searchBtn = document.getElementById('searchTermBtn'); -searchBtn.addEventListener('click', updateTerm); \ No newline at end of file +searchBtn.addEventListener('click', updateTerm);