Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@haraken_qiita

[vue.js] ストップウォッチのコンポーネントを自作

ストップウォッチをvue.jsコンポーネントで実装してみました。
自作のブラウザゲームでクリア時間を計るのに使ってます。

実行画面

image.png
時間は小数2桁まで表示。
Start/Stop ボタンと Reset ボタンを表示、ラップの記録機能は無し。

ソースコード

stopWatch.vue
<template>
<div>
    <p>{{interval.toFixed(2)}}</p> <!-- 小数2桁まで表示 -->
    <button @click="startTimer()" v-show="!active">Start</button>
    <button @click="stopTimer()" v-show="active">Stop</button>
    <button @click="resetTimer()">Reset</button>
</div>
</template>

<script>
export default {
    name: 'stopWatch',
    data(){
        return {
            active : false, // 実行状態
            start : 0, // startを押した時刻
            timer : 0, // setInterval()の格納用
            interval : 0, // 計測時間
            accum : 0, // 累積時間(stopしたとき用)
        }
    },
    methods:{
        startTimer(){
            this.active = true;
            this.start = Date.now();
            this.timer = setInterval(()=>{ this.interval = this.accum + (Date.now() - this.start) * 0.001;}, 10); // 10msごとに現在時刻とstartを押した時刻の差を足す
         },
        stopTimer(){
            this.active = false;
            this.accum = this.interval;
            clearInterval(this.timer);
        },
        resetTimer(){
            this.interval = 0;
            this.accum = 0;
            this.start = Date.now();
        }
    }
}
</script>
0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?