Skip to content

Commit

Permalink
script.js (song tracker) improvement in code in efficiency
Browse files Browse the repository at this point in the history
Made changes raised by issue #169
  • Loading branch information
vyanky1227 committed May 15, 2024
1 parent 4a598eb commit 742aa5f
Showing 1 changed file with 32 additions and 17 deletions.
49 changes: 32 additions & 17 deletions Song Tracker/scripts/script.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 = '<p>No results found.</p>';
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
Expand All @@ -42,6 +40,23 @@ const updateTerm = () => {
});
};

const displayResults = (results, container) => {
if (results.length === 0) {
container.innerHTML = '<p>No results found.</p>';
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');
Expand Down Expand Up @@ -82,4 +97,4 @@ const togglePlay = (audioUrl) => {

// Initialize search button event listener
const searchBtn = document.getElementById('searchTermBtn');
searchBtn.addEventListener('click', updateTerm);
searchBtn.addEventListener('click', updateTerm);

0 comments on commit 742aa5f

Please sign in to comment.