【发布时间】:2020-09-09 01:34:48
【问题描述】:
我对编程有点陌生,但最近我试图做我的第一个项目,称为计时器计数,它只是一个简单的本地网站,当我决定在白天开始编程时打开它,它计算时间。我创建了 2 个具有 2 个不同功能(开始、停止)的按钮,但我遇到的问题是我不知道如何实现停止功能。这个想法是计时器应该在按钮点击后停止,当我点击开始按钮时,它应该从保存的时间开始。 这是 HTML/CSS 代码:
<div class="timer-display-id">
<h1>Timer </h1>
<p id="timer">00:00:00 </p>
<button id="start-timer" onclick="start()">Start </button>
<button id="stop-timer" onclick="stop()">Stop </button>
</div>
<script src="timer.js"></script>
这是 JS 代码:
function stop() {
// not exactly sure if this function should be here, anyway no idea what to add to get this to work
clearInterval(interval);
start.disabled = false;
}
function convertSec(cnt) {
let sec = cnt % 60;
let min = Math.floor(cnt / 60);
if (sec < 10) {
if (min < 10) {return "0" + min + ":0" + sec;}
else {return min + ":0" + sec;}
}
else if ((min < 10) && (sec >= 10)) {return "0" + min + ":" + sec;}
else {return min + ":" + sec;}
}
function start() {
let ret = document.getElementById("timer");
let counter = 0;
let start = document.querySelector("#start-timer");
let stop = document.querySelector("#stop-timer");
start.disabled = true;
let interval = setInterval(function() {
ret.innerHTML = convertSec(counter++); // timer start counting here...
},1000);
}
我知道这可能很混乱,有点缺乏逻辑,但我现在能做的最好。如果您想提供一些有关代码组织的提示,我将不胜感激。
【问题讨论】:
-
这主要是一个范围问题;您需要在您的函数之外声明
interval,否则stop无权访问它。它当前位于您的start函数的本地,并且在函数完成后不再存在。 -
感谢 Chris 的建议,你是对的,我的问题是声明一个局部变量而不是全局变量。
标签: javascript timer