为什么我的定时器消除不了
来源:3-13 编程练习
好学生慕小帅
2022-07-30 10:05:01
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<style>
div {
width: 300px;
margin: 20px 0;
line-height: 30px;
background: yellowgreen;
}
</style>
</head>
<body>
<button id="start">开始</button>
<button id="stop">停止</button>
<div id="box"></div>
<script>
const startBtn = document.getElementById('start')
const stopBtn = document.getElementById('stop')
const box = document.getElementById('box')
var show = {
content: "Hello World",
timer: null,
start: function () {
start.addEventListener(
'click',
() => {
var time = setInterval(() => {
box.innerHTML += this.content + ' ';
},1000)
}
)
},
stop: function () {
stop.onclick = function() {
clearInterval(time);
}
},
}
show.start();
show.stop();
</script>
</body>
</html>1回答
好帮手慕久久
2022-07-30
同学你好,代码有如下问题:
1、当元素有id时,可以直接利用id操作元素,而不用获取元素,比如:

但是这样写,会存在未知的问题。比如同学的代码中,没有用变量startBtn、stopBtn绑定事件,效果就受到了影响。
调整如下:


2、开始按钮中,声明的定时器变量time,是局部变量:

它不能在结束按钮的事件处理函数中使用,所以无法清除定时器。
修改如下:

祝学习愉快!
相似问题