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
pull/212/head
Kelvin Yeboah 9 months ago committed by GitHub
parent 9409685c9a
commit 5634f00e77
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -1,21 +1,23 @@
const counters = document.querySelectorAll('.counter') const counters = document.querySelectorAll('.counter');
counters.forEach(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 updateCounter = () => {
const target = +counter.getAttribute('data-target') // If the counter hasn't reached the target
const c = +counter.innerText if (current < target) {
current += increment; // Increment counter
counter.innerText = Math.ceil(current); // Update the inner text with rounded value
const increment = target / 200 // Use requestAnimationFrame for smoother animation
requestAnimationFrame(updateCounter);
if(c < target) {
counter.innerText = `${Math.ceil(c + increment)}`
setTimeout(updateCounter, 1)
} else { } else {
counter.innerText = target counter.innerText = target; // Ensure the target value is set when done
} }
} };
updateCounter() // Start the counter animation
}) updateCounter();
});

Loading…
Cancel
Save