Is updateCounter defined again for each element in the array?

Hello all,

How many times is it defined? Since the function declaration is in forEach(), i assume that it is declared three times. Is that true?

const followerNumbers = document.querySelectorAll(".follower-numbers");

followerNumbers.forEach((x) => {
	x.innerText = "0";

	const target = +x.getAttribute("data-target");
	const increment = target / 200;
	const updateCounter = () => {
		//console.log("updateCounter Tanımlandı");
		const c = parseInt(x.innerText);

		if (c < target) {
			x.innerText = `${Math.ceil(c + increment)}`;
			setTimeout(updateCounter, 1);
		} else {
			x.innerText = target;


//Are we defining updateCounter method for each of the elements?

You can find the whole project here.

Yes, I believe it is separately defined.

1 Like

It is re-declared on every loop iteration.

You can move it outside the forEach and pass it the arguments it needs. I’d suggest using setInterval instead of setTimeout as well.

1 Like

Hi @lasjorg, yeah i think setInterval is a way better idea but in the tutorial that i’am following tutor did that so i was trying to understand.

Thank you for your answer.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.