본문 바로가기

Web/Vue

[Vue] 본인인증 sms 3분 유효체크 타이머

 

setInterval

 

let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)

 

setInterval은 함수를 주기적으로 실행하게 만듭니다.

함수 호출을 중단하려면 clearInterval(timerId)을 사용하면 됩니다.

 

예제

Vue 에서 3분타이머 만들기

export default {
  name: "Timer",
  data: function() {
    return {
      Timer: null,
      TimeCounter: 180,
      TimerStr: "03:00"
    };
  },
  mounted: function() {
    //문자발송성공시 호출
    if(this.Timer != null){
    	this.timerStop(this.Timer);
        this.Timer = null;
    }
    this.Timer = this.timerStart();
  },
  methods: {
    timerStart: function() {
      // 1초에 한번씩 start 호출
      this.TimeCounter = 180;
      var interval = setInterval(() => {
        this.TimeCounter--; //1초씩 감소
        this.TimerStr = this.prettyTime();
        if (this.TimeCounter <= 0) this.timerStop(interval);
      }, 1000);
      return interval;
    },
    timerStop: function(Timer) {
      clearInterval(Timer);
      this.TimeCounter = 0;
    },
    prettyTime: function() {
      // 시간 형식으로 변환 리턴
      let time = this.TimeCounter / 60;
      let minutes = parseInt(time);
      let secondes = Math.round((time - minutes) * 60);
      return (
        minutes.toString().padStart(2, "0") +
        ":" +
        secondes.toString().padStart(2, "0")
      );
    },
  },
};

 

참조:

https://ko.javascript.info/settimeout-setinterval

https://nayha.tistory.com/569