Publish/JavaScript

[ 숫자 카운트 ] 스크롤시 setTimeout 실행 //하지만 무한반복된다

아2 2022. 4. 2. 22:29
 //숫자 카운트
  function numberCounter(target_frame, target_number) {
    this.count = 0; this.diff = 0;
    this.target_count = parseInt(target_number);
    this.target_frame = document.getElementById(target_frame);
    this.timer = null;
    this.counter();
  };
  numberCounter.prototype.counter = function () {
    var self = this;
    this.diff = this.target_count - this.count;

    if (this.diff > 0) {
      self.count += Math.ceil(this.diff / 5);
    }

    this.target_frame.innerHTML = this.count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    if (this.count < this.target_count) {
      this.timer = setTimeout(function () { self.counter(); }, 30);
    } else {
      clearTimeout(this.timer);
    }
  };

  $(window).scroll(function () {
    var scrollTop = $(window).scrollTop();
    var winH = $(window).innerHeight() / 4;
    var mainNavTop = $(".ratio_percent").offset().top;


    if (scrollTop + winH >= mainNavTop) {
      
      var timeOut = setTimeout(function () {
        new numberCounter("number1", 78);
        new numberCounter("number2", 70);
        new numberCounter("number3", 74);
        new numberCounter("number4", 45);
        new numberCounter("number5", 15);
        new numberCounter("number6", 10);
      });
    } 
    
    if (scrollTop + winH -30 >= mainNavTop) {
      clearTimeout(timeOut)
    }
  });

마지막

if (scrollTop + winH -30 >= mainNavTop) {
      clearTimeout(timeOut)
    }
 
 
해당 코드를 추가함으로써 .. 특정 구간에서만 settimeout이 실행되도록 함.
만약 이게 없으면,
특정 영역 지나서부터 카운트가 미친듯이 계속 빙글빙글 돌아감.
 
다행히 모바일에서도 적당한 위치에서 잘 돌아가서 다행.

 

- 굳이 이 코드를 넣은 이유는, 구조가 어떻든 간에 이벤트 넣는게 쉬워서. 실행하고싶으면 클래스에 number 값만 주면 됨.