请老师检查一下作业
来源:3-13 编程练习
激情的樱木花道
2021-07-01 08:36:52
<!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')
let timers;
var show = {
content: "Hello World",
timer: null,
start: function () {
startBtn.onclick=()=>{
timers=setInterval(()=>{
box.innerHTML+=`${this.content} `;
},1000)
}
},
stop: function () {
stopBtn.onclick=function(){
clearInterval(timers);
}
},
}
show.start();
show.stop();
</script>
</body>
</html>
1回答
同学你好,代码没有语法错误,只是存在一个小bug。当多次点击“开始”按钮时,div#box中的内容出现的速度会加快:

原因是每点击一次“开始”按钮,就会开启一个定时器。定时器叠加,就会造成div#box中的内容出现的速度增快。
建议点击开始按钮之前,将之前的定时器清掉:

另外,代码可以优化一下:
对象show中,已经定义了timer,可以用它来存储定时器,不用在全局中再次定义变量timers:

祝学习愉快!
相似问题