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>
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();
})
}
});
注意
きちんと制御しないとSTARTをクリックする度タイマーが発動し、荒ぶる。