JavaScript - How to update numbers when displayed on the viewport but prevent the code from running again when keeping scrolling

This code updates numbers. However, it runs again and again on every scroll. I would like the numbers to be updated only once when I see them on the viewport. Then, the function can run again if I scroll past the viewport and reach the numbers again.

Here is my code:

class Counter {

  constructor(id, target, speed, appendString) {

    this.id = id;

    this.target = target;

    this.speed = speed;

    this.appendString = appendString;

  }

  start() {

    const container = document.querySelector(this.id);

    container.innerText = 0;

    let count = 0;

    function updateCount(counter, target, speed, appendString) {

      if (count < target) {

        counter.innerText = `${count} ${appendString}`;

        count++;

        setTimeout(

          () => updateCount(counter, target, speed, appendString),

          speed

        );

      } else {

        counter.innerText = `${target} ${appendString}`;

      }

    }

    updateCount(container, this.target, this.speed, this.appendString);

  }

}

const counter1 = new Counter('#headline-e6423da8', 156, 15, '');

const counter2 = new Counter('#headline-77ad9299', 227, 15, '');

const counter3 = new Counter('#headline-8255ec52', 91, 15, '%');

const counter4 = new Counter('#headline-5e08a0cb', 30, 15, '+');

window.addEventListener('scroll', () => {

  counter1.start();

  counter2.start();

  counter3.start();

  counter4.start();

});
1 Like

Optimizing JavaScript Code for Viewport Updates: A Comprehensive Guide

The provided JavaScript code updates numbers on every scroll, impacting performance. This article addresses the issue by introducing Intersection Observer for efficient updates when numbers are in the viewport.

Updating numbers on every scroll affects website performance, necessitating the optimization of JavaScript code.

Understanding the Problem

Continuous updates strain system resources, prompting the need to modify the code for selective updates when numbers are visible.

Viewport Awareness

Utilizing the Intersection Observer API enables targeted updates, optimizing performance by triggering functions only when elements are in the viewport.

Code Analysis

A breakdown of the code identifies the section responsible for repetitive updates, guiding a focused solution.

Implementing Intersection Observer

A step-by-step guide on integrating Intersection Observer ensures efficient updates and improved user experience.

Optimizing Code for Performance

Efficient code contributes to a smoother user experience, and this section provides tips for improvement.

Testing and Debugging

Thorough testing is emphasized, with solutions for common issues during implementation.

Benefits of the Solution

Implementing the provided solution positively impacts website performance.

User-Friendly Explanations

Complex concepts are simplified for developers of all skill levels, ensuring accessibility.

Real-world Examples

Practical scenarios illustrate the significance of the proposed solution in diverse projects.

User Experience Considerations

Optimized code positively influences the user experience, emphasizing its importance in development.

Best Practices

Additional best practices for writing efficient JavaScript code encourage continuous improvement.

Common Mistakes to Avoid

Guidance on avoiding common errors helps developers steer clear of pitfalls.

Conclusion

Summarizing key points, the article highlights the significance of optimizing JavaScript code for a high-performance website.