I am working on a site that has a lot of counters and I have a problem getting the [data-speed] to create different counter speeds depending on the number in that counter.
When I run this forEach loop I always get the same speed, the function gets the largest number from all the counters.
Any idea where I went wrong?
const counters = document.querySelectorAll('.counter');
let i = 0;
const io = new IntersectionObserver(entries => {
entries.forEach(entry => {
const finalNumber = entry.target.innerText;
const speed = +entry.target.dataset.speed;
if (entry.isIntersecting) {
entry.target.innerText = i;
const interval = setInterval(() => {
entry.target.innerText = i += speed;
if (i >= finalNumber) {
entry.target.innerText = finalNumber;
clearInterval(interval);
}
}, 10)
}
})
})
counters.forEach(item => io.observe(item))
<h1 class="counter" data-speed="1">1000</h1>
<h1 class="counter" data-speed="2">1000</h1>
<h1 class="counter" data-speed="3">1000</h1>
<h1 class="counter" data-speed="4">1000</h1>
<h1 class="counter" data-speed="5">1000</h1>