这个问题在这里已有答案:
我想在JavaScript
中第一次使用面向对象的Javascript创建一个启动和停止计时器。我没有启动计时器的问题。问题是打败它,因为即使我使用clearInterval
或clearTimeout
,它也不会停止。请问我的代码有什么问题,并且我可以解决它吗?
function StopWatch() {
let timer = 0;
let starter = function() {
setInterval(function() {
++timer;
}, 1000);
// if(this.start) {
// throw new Error(`Timer already started`);
// }
console.log(timer);
};
let stopper = function() {
window.clearTimeout(starter);
console.log(timer)
};
this.start = starter;
this.stop = stopper;
}
const sw = new StopWatch();
console.log(sw);
谢谢。
setInterval
函数返回一个引用,您将其传递给clearInterval
:
const interval;
//...
interval = setInterval(...);
//...
clearInterval(interval);