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: "",
timeLimit: 5 * 1000,
bonus: false,
bonusTime: 5 * 1000,
},
methods: {
startTimer() {
this.startTime = Date.now();
this.updateTimer();
},
addTime() {
this.bonus = true;
},
updateTimer() {
let timeLeft = this.startTime + this.timeLimit - Date.now();
if(this.bonus) {
timeLeft = timeLeft + this.bonusTime;
this.bonus = false;
}
this.timer = (timeLeft /1000).toFixed(2);
console.log(this.timer);
const timeoutId = setTimeout( () => {
this.updateTimer();
}, 10);
if(timeLeft < 0) {
clearTimeout(timeoutId);
alert("Finished");
}
}
}
})