計時器setTimeout()
<!DOCTYPE html>
<html>
<head>
? <meta charset="UTF-8">
? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? <title>Document</title>
</head>
<body>
<input type="text" id="txt" />
<button onclick="startCount()">開始計數!</button>
<button onclick="stopCount()">停止計數!</button>
<script type="text/javascript">
? var c = 0;
? var t;
? var timer_is_on = 0;
? function timedCount() {
? ? ? document.getElementById("txt").value = c;
? ? ? c = c + 1;
? ? ? t = setTimeout(function(){timedCount()}, 1000);
? }
??
? function startCount() {
? ? ? if (!timer_is_on) {
? ? ? ? ? timer_is_on = 1;
? ? ? ? ? timedCount();
? ? ? }
? }
??
? function stopCount() {
? ? ? clearTimeout(t);
? ? ? timer_is_on = 0;
? }
? </script>
</body>
</html>
2018-03-05
不如把計時器的那個函數綁在按鈕上,一旦點擊按鈕自動開始多次調用。清除定時器也一樣,綁在按鈕上比較好。希望對你有幫助