老师,请检查下
来源:3-13 编程练习
Lanny_Chung
2022-04-21 11:57:27
<!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 = () => { this.timer = setInterval(() => { this.content += " Hello World"; box.innerHTML = this.content; }, 1000); } }, // 在此补充代码 stop:function(){ stopBtn.onclick = ()=>{ clearInterval(this.timer); } } } // 在此补充代码 show.start(); show.stop(); </script> </body> </html>
1回答
同学你好,代码存在如下问题:
1、多次快速点击“开始”按钮时,box中的内容增加的越来越快。原因是每点击一次按钮,就会开启一个定时器,导致定时器累积,从而内容增加的越来越快。
建议点击开始按钮后,先清除之前可能存在的定时器,再开启新的,保证每次只有一个定时器:
2、点击开始按钮后,定时器第一次启动,box会同时增加两个“Hello World”:
建议调整代码顺序:
祝学习愉快!
相似问题