-1

i just want to call this code as a function inside an IntersectionObserver:

And i want it to be reusable and cleaner, so i could just it anywhere

//I want this to be a function
numbers.forEach((number, index) => {
    intervals[index] = setInterval(() => {
        if(counters[index] === parseInt(number.dataset.num)){
            clearInterval(counters[index]);
        } else{
            counters[index] += 1;
            number.textContent = counters[index] + "%";
            svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));
        }
    }, 20);
 });
}

My IntersectionObserver

const animate = new IntersectionObserver(function (entries, animate) {
  entries.forEach(entry => {
    if(!entry.isIntersecting) {
   //function
    }
  });
});
animate.observe(test);
newbcods
  • 9
  • 4
  • what function? the first code? well, the first code seems to depend on `numbers` `intervals`, `counters` and `svgEl` - whatever all those things are - so, not sure how to help – Jaromanda X Nov 22 '22 at 09:52
  • i edited my question, you may want to take a look. basically i want the first code to be a reusable function that i can call anywhere – newbcods Nov 22 '22 at 11:54

1 Answers1

0

I don't see the point!

Enclose your function in function name either function... or const... and call it in intersection observer

function numbersCount(numbers) {
  numbers.forEach((number, index) => {
    intervals[index] = setInterval(() => {
        if(counters[index] === parseInt(number.dataset.num)){
            clearInterval(counters[index]);
        } else{
            counters[index] += 1;
            number.textContent = counters[index] + "%";
            svgEl[index].style.strokeDashoffset = Math.floor(472 - 440 * parseFloat(number.dataset.num / 100));
        }
    }, 20);
   });
  }
}

Now that means that "numbers" is known somewhere! From what you are showing, I can't guess

pier farrugia
  • 1,520
  • 2
  • 2
  • 9
  • yah. like this but is forEach okay inside of a `function funcName()` ? shouldnt we use .maps? – newbcods Nov 22 '22 at 11:56
  • foreach working without problems. – pier farrugia Nov 22 '22 at 14:57
  • oh. i thought its not good using forEach when iteration. thats what others said – newbcods Nov 23 '22 at 00:53
  • yes, lot of reading on how bad is forEach, too slow mainly... Now, depends of what you are doing! Iteration on 10, 20... 50 items, won't change a lot in speed between foreach and "for" loop. Lot of my foreach use is in node list after queryselectorall, syntax is great for that, and I never have thousand of nodes – pier farrugia Nov 23 '22 at 08:54