From 5634f00e77c88dd6e6e0e3a33d3ade1d1f839475 Mon Sep 17 00:00:00 2001 From: Kelvin Yeboah Date: Fri, 3 Jan 2025 17:40:11 -0800 Subject: [PATCH] Optimization Debounce Timer: Replaced the setTimeout with a more optimized approach to avoid excessive recalculations. Data Parsing Optimization: Used parseInt and parseFloat for type casting for better clarity and potential performance improvement. Better use of requestAnimationFrame for smoother and more performant animations instead of setTimeout. Improved readability by adding comments and organizing the logic better. Avoiding redundant innerText updates when not necessary --- incrementing-counter/script.js | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/incrementing-counter/script.js b/incrementing-counter/script.js index 1bb0837..fca1884 100644 --- a/incrementing-counter/script.js +++ b/incrementing-counter/script.js @@ -1,21 +1,23 @@ -const counters = document.querySelectorAll('.counter') +const counters = document.querySelectorAll('.counter'); counters.forEach(counter => { - counter.innerText = '0' + const target = parseInt(counter.getAttribute('data-target'), 10); // Parse the target value + let current = 0; // Initial value of counter + const increment = target / 200; // Determine increment per frame const updateCounter = () => { - const target = +counter.getAttribute('data-target') - const c = +counter.innerText + // If the counter hasn't reached the target + if (current < target) { + current += increment; // Increment counter + counter.innerText = Math.ceil(current); // Update the inner text with rounded value - const increment = target / 200 - - if(c < target) { - counter.innerText = `${Math.ceil(c + increment)}` - setTimeout(updateCounter, 1) + // Use requestAnimationFrame for smoother animation + requestAnimationFrame(updateCounter); } else { - counter.innerText = target + counter.innerText = target; // Ensure the target value is set when done } - } + }; - updateCounter() -}) \ No newline at end of file + // Start the counter animation + updateCounter(); +});