1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptでストップウォッチを実装する

Last updated at Posted at 2021-02-15

#やりたいこと
久しくJavaScriptを触っていないため思い出すために、
簡単なJavaScriptで以下の様な、STARTボタンを押下後にストップウォッチを起動させ、ストップボタンで止めることをする。
screencast 2021-02-15 23-01-28.gif

コードは以下の通り
複雑ではないのでHTMLに直接記載

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="./style.css">

    <title>TIMER</title>
</head>
<body>
    <div class="container">
        <p id="timer">00:00:00</p>

        <div>
            <button id="start_stop" class="btn btn-lg btn-primary">START</button>
        </div>
    </div>

    <script>
        var start;
        var timer_id;
        document.getElementById('start_stop').addEventListener('click', function(){
            if (this.innerHTML === 'START') {
                start = new Date();
    
          // 一定時間ごとに特定の処理を繰り返す(10ミリ秒)
                timer_id = setInterval(goTimer, 10);
    
                // STOPボタンにする
                this.innerHTML = 'STOP'
                this.classList.remove('btn-primary');
                this.classList.add('btn-danger');
            } else {
                clearInterval(timer_id);

                this.innerHTML = 'START'
                this.classList.remove('btn-danger');
                this.classList.add('btn-primary');
            }
        })

        var addZero = function(value) {
            if (value < 10) {
                value = '0' + value;
            }
            return value;
        }

        var goTimer = function() {
            var now = new Date();

       // 現在の時間をSTARTした時間から引いて経過時間を計算
            var milli = now.getTime() - start.getTime();
            var seconds = Math.floor(milli / 1000);
            var minutes = Math.floor(seconds / 60);
            var hours = Math.floor(minutes / 60);

            seconds = seconds - minutes * 60;
            minutes = minutes - hours * 60;

       // innerHTMLの要素を書き換える
            document.getElementById('timer').innerHTML = addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds);
        }
    </script>
</body>
</html>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?