LoginSignup
1
3

More than 5 years have passed since last update.

[js] よく出るsetTimeoutのテンプレート

Last updated at Posted at 2016-01-27

setTimeoutの典型的な使い方

javaScriptのsetTimeout関数の使い方をタイマーを例としてメモ。

timer.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>TimerTest</title>
</head>
<body style="text-align:center">
    <p id="timer">0.00</p>
    <button id="start">START</button>
    <button id="stop">STOP</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="timer.js"></script>
</body>
</html>

スクリーンショット 2016-01-28 00.03.34.png

timer.js
$(function() {
    var timer;  //setTimeout closure
    var stTime = 0; //start time
    var runFlag = false;    //check timer run

    $('#start').click(function() {
        if(runFlag) return; //prevent repitition
        runFlag = true;
        stTime = $.now();
        updateTimer();
    });

    $('#stop').click(function() {
        if(!runFlag) return;
        runFlag = false;
        clearTimeout(timer);
    })

    function updateTimer() {
        timer = setTimeout(function() {
            var t = $.now() - stTime;
            $('#timer').text((t / 1000).toFixed(2));
            updateTimer();
        })
    }
});

スクリーンショット 2016-01-28 00.03.54.png
おわり。

注意

きちんと制御しないとSTARTをクリックする度タイマーが発動し、荒ぶる。

1
3
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
3