Vue

by cedric_tarou

HTML

<div id="app">
  <h2>timer</h2>
  <div>{{ timer }}</div>
  <div><button @click="startTimer()">start</button></div>
  <div><button @click="addTime()">addTime</button></div>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

Vue

new Vue({
  el: "#app",
  data: {
		timer: "0.00",
    startTime: "",
    bonusTime: 2 * 1000,
    leftTime: 5 * 1000,
  },
  methods: {
  //タイマーをスタートさせる
  	startTimer() {
    	this.startTime = Date.now();
      this.updateTimer();
    },
    addTime() {
 //addボタンを押すとボーナスタイムが追加されるように処理したい。
      this.leftTime = this.leftTime + this.bonusTime;
      console.log(this.leftTime);
    },
    updateTimer() {
    //タイマーの中身
    	let diff;
			diff = this.leftTime - (Date.now() - this.startTime);
      this.timer = (diff /1000).toFixed(2);
    //タイマーの表示が更新される処理
      const timeoutId = setTimeout( () => {
      this.updateTimer();
      }, 10);
      //タイマーが0になるとアラートが出るようにする
      if(diff < 0) {
        clearTimeout(timeoutId);
        alert("Finished");
      }
    }
  }
})