2017-11-11 1 views
0

vue.js를 사용하여 타이머를 만들려고했지만 몇 가지 문제가 있습니다.두 가지 문제점 : this.myMethod가 addEventListner에 의해 추가 된 function-click 이벤트가 아니기 때문에 사용자가 클릭 할 때 더 많은 횟수가 발생합니다.

다음
methods: {   
    saveRunningMethod() { 
     var runningData = { 
      duration: `${this.hour} : ${this.minute} : ${this.second}`, 
      username: this.$store.state.user.username 
     } 
     this.$store.dispatch('saveRunning' , runningData) 
     console.log(runningData); 
    }, 
    startTimer(){  
     this.isTimerStart = true; 
     var timer = window.setInterval(() => { 

      var e = document.getElementById("stopBtn") 
      e.addEventListener("click", function(){ 
       clearInterval(timer) 
       this.isTimerStart = false; 
       console.log("lets Save it") 
       this.saveRunningMethod() 
       }); 

      if(this.mSecond < 9) 
       this.mSecond +=1 
      else 
       this.mSecond=0 

      if(this.mSecond==9) 
       this.second +=1     

      if(this.second>59)     
       this.second=0 

      if(this.second==59) 
       this.minute +=1 

      if(this.minute>59) 
       this.minute = 0 

      if(this.minute==59) 
       this.hour +=1    

    },100); 

    } 
} 

, 내 e.addEventListener("click", function(){ 내 정지 버튼을 클릭합니다,하지만 당신은이 사진에서 볼 수있는대로,이 방법은 여러 번 실행 보인다 때 타이머를 중지, 내 CONSOLE.LOG이 내 mtehods 섹션입니다 33 번 같이 달린다! 그게 왜? 내 startTimer() 방법 내에서이 방법을 실행 this.saveRunningMethod()하지만 "this.saveRunningMethod() is not a function" 오류 :

enter image description here

나의 다른 질문은,이 라인에 관한 것입니다!

마지막으로 더 나은 솔루션을 알고 있다면 setInterval을 사용하여 타이머를 만들었습니다. 정말 감사하겠습니다.

업데이트 : 나는

<div class="row p-2 m-3 mt-3"> 
     <div class="col-12 p-0 animated fadeInUp mt-3"> 
      <p class="text-center">Your last record was : 00:00:00</p> 
     </div> 
     <div class="col-12 p-0 animated fadeInUp mt-3"> 
      <h1 class="text-center timer"> 
       {{this.hour}}:{{this.minute}}:{{second}}:{{mSecond}} 
      </h1> 
     </div> 
    </div> 
    <div class="row p-2 mt-3" v-bind:class="[this.isTimerStart==false ? 'show' : 'hide']"> 
     <div class="col-12 p-0 animated tada text-center"> 
      <button class="btn-link timerImg" @click="startTimer()"> 
       <img class="img-fluid timerImg" src="../../static/timerStart.png" /> 
       <p>Start</p> 
      </button> 
     </div> 
    </div> 

    <div class="row p-2 mt-3" v-bind:class="[this.isTimerStart ? 'show' : 'hide']"> 
     <div class="col-12 p-0 animated tada text-center"> 
      <button id="stopBtn" class="btn-link timerImg"> 
       <img class="img-fluid timerImg" src="../../static/timerStop.png" /> 
       <p>Stop</p> 
      </button> 
     </div> 
    </div> 

감사합니다 내 HTML 부분에 추가합니다.

+0

가 명확하지 않다,하여 여러개의 시간을 실행하는 타이머가 이유. 질문을 편집하고 HTML 부분도 추가하십시오. – WaldemarIce

+0

@WaldemarIce 내 HTML 부분은 타이머와 버튼 두 개를 표시하는 div 중 하나입니다. 질문을 업데이트하고 어쨌든 추가합니다. 감사. –

+0

한 번에 한 가지 질문 만하십시오. https://stackoverflow.com/help/how-to-ask – Rob

답변

1

According to MDN,이 window.setInterval()가하는 일입니다 :

는 그 함수를 호출 할 때마다 사이의 고정 된 시간 지연, 반복적으로 함수를 호출합니다.

따라서 startTimer() 메서드가 실행될 때마다 100 밀리 초마다 중지 단추에 click 이벤트 수신기가 추가됩니다. 중지를 클릭하기 전에

var timer = window.setInterval(() => { 

    var e = document.getElementById("stopBtn") 
    e.addEventListener("click", function() { 
     // This code will execute 33 times when the stop button is clicked. 
    }) 
    ... 
}, 100) 

페이지를로드하고 5.4 초를 기다리면 : 페이지를로드하고 정지 버튼을 클릭하기 전에 3.3 초 정도 기다린 경우 click 이벤트 리스너는 버튼에 33 시간을 추가 한 것입니다 그래서 버튼을 누르면 click 이벤트 리스너가 버튼에 54 번 추가됩니다!

window.setInterval()을 사용하는 대신 window.setTimeout()을 사용해야합니다.

지정된 지연 후 코드 스 니펫이나 함수를 실행합니다.

즉, window.setTimeout()은 지정된 지연 후 한 번만 실행되는 타이머를 만듭니다.

this.saveRunningMethod() is not a function 것으로하여 컨텍스트 addEventListener()에 전달 된 콜백 함수 내에서 변화되어있는 오류에 대해서는

때문에 this 값 버튼 자체가 아닌 객체가된다. 이를 피하기 위해 addEventListener()에 화살표 기능을 전달할 수 있습니다. 이것은 (this의 값이 개체를 유지됩니다 화살표 기능 내부 있도록) 컨텍스트가 변경되지 않은 상태로 유지하게됩니다 : 코드에서

window.setTimeout(() => { 
    var e = document.getElementById("stopBtn") 
    e.addEventListener("click",() => { 
     this.isTimerStart = false; 
     console.log("lets Save it"); 
     this.saveRunningMethod(); 
    }); 
}, 100) 
+0

답을 주셔서 감사합니다. 모든 것을 설명합니다. setTimeout을 사용하여 setTimeout을 설정하지 못했기 때문에 타이머를 만들려면 다른 방법을 찾아야한다고 생각합니다. 또한 addEventListener()에 화살표 함수를 추가하면 두 번째 질문에 대한 문제가 해결되었습니다. –

관련 문제