如何通过按开始按钮来打开时钟。如果我按START几次,时间会更新,但我只需按一次即可每秒更新一次。目前还不清楚为什么递归函数调用不起作用。
<!DOCTYPE HTML>
<html>
<body>
<input type="button" onclick="clock.clockStart()" value="Start">
<input type="button" onclick="clock.clockStop()" value="Stop">
<div class='clocks'>
<span class='hours'></span>
<span class='minutes'></span>
<span class='seconds'></span>
</div>
<script>
'use strict';
class Clock {
constructor() {
this.hh = document.querySelector('.hours');
this.mm = document.querySelector('.minutes');
this.ss = document.querySelector('.seconds');
}
clockStart() {
let self = this;
self.date = new Date();
self.timer = setTimeout(function tick1() {
self.hh.textContent = '' + self.date.getHours();
self.mm.textContent = ': ' + self.date.getMinutes();
self.ss.textContent = ': ' + self.date.getSeconds();
self.timer = setTimeout(tick1, 1000);
}, 1000);
}
clockStop() {
clearTimeout(this.timer);
}
}
let clock = new Clock();
</script>
</body>
</html>
&#13;
谢谢。
答案 0 :(得分:4)
在您的代码中设置self.date = new Date();
这是该时间点的时间戳。它不会继续更新。
因此,如果您想要更改时间,则需要将其移动到计时器内并在每次迭代时声明它。
self.timer = setTimeout(function tick1() {
self.date = new Date();
/* rest of your code */
答案 1 :(得分:1)
我做了一些更改并添加了评论来解释我为何做出更改。我希望这说清楚。
<!DOCTYPE HTML>
<html>
<body>
<input type="button" onclick="clock.clockStart()" value="Start">
<input type="button" onclick="clock.clockStop()" value="Stop">
<div class='clocks'>
<span class='hours'></span>
<span class='minutes'></span>
<span class='seconds'></span>
</div>
<script>
'use strict';
class Clock {
constructor() {
this.hh = document.querySelector('.hours');
this.mm = document.querySelector('.minutes');
this.ss = document.querySelector('.seconds');
}
clockStart() {
// There is no need for self. You're using ES6 and thus you have fat
// arrow methods that keep the this reference the same.
// Use setInterval instead of useTimeout, you want this to be called
// every second. In addition, using a fat arrow function will make sure
// this still refers your instance of the Clock class.
this.timer = setInterval(() => {
// You need to refresh date each time before showing it in your UI.
this.date = new Date();
this.hh.textContent = '' + this.date.getHours();
this.mm.textContent = ': ' + this.date.getMinutes();
this.ss.textContent = ': ' + this.date.getSeconds();
}, 1000);
}
clockStop() {
// When stop is clicked, cancel the interval.
clearInterval(this.timer);
}
}
let clock = new Clock();
</script>
</body>
</html>
&#13;