请老师看下对不对?
<!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 () {
startBtn.onclick = () => {
timer= setInterval(() => {
console.log(this.timer++);
box.innerHTML += this.content;
}, 1000);
// clearInterval(this.timer)
}
},
stop: function () {
stopBtn.onclick = () => {
clearInterval(timer)
}
},
}
show.start();
show.stop();
</script>
</body>
</html>老师你好,多次点击后会加速,注释部分点击开始先清除定时器不知道放哪里,都试了没效果。
12
收起
正在回答 回答被采纳积分+1
2回答
好帮手慕久久
2022-07-05 09:52:49
同学你好,解答如下:
1、如下代码中的timer,并不是同一个timer,所以无法清除定时器:

2、如下写法是可以的:

这样写就可以了。
3、如果想实现同学的需求,可以参考如下思路:
<!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,
lock: true, //设置一个锁
start: function () {
startBtn.addEventListener("click", () => {
// 如果关锁了,就不再往下执行--》即 不再开启新的定时器
if(!this.lock) return
// 初始时,锁没关,则会开启一个定时器
this.timer = setInterval(() => {
box.innerHTML += (this.content + " ")
}, 1000)
// 定时器一旦开启,就关锁--》以后再连续点击,也不重新生成定时器
this.lock = false
}, false)
},
stop: function () {
stopBtn.addEventListener("click", () => {
// 清空定时器
clearInterval(this.timer)
// 把锁打开
this.lock = true;
}, false)
},
}
// 在此补充代码
show.start()
show.stop()
</script>
</body>
</html>祝学习愉快!

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星