请老师帮我看看截流锁好像没有用

来源:3-13 编程练习

听的说

2022-01-03 22:53:59

<!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 show = {
content: "Hello World ",
timer: null,
lock: true,
start: function() {
// 在此补充代码
if (!this.lock) return;
startBtn.addEventListener('click', () => {
clearInterval(this.timer);
this.timer = setInterval(() => {
box.innerHTML += "<span>" + this.content + "</span>";
}, 1000);
}, false);
this.lock = false;
setTimeout(function() {
this.lock = true;
console.log(this.lock);
}, 2000)
},
stop: function() {
// 在此补充代码
stopBtn.addEventListener('click', () => {
clearInterval(this.timer);
}, false);
},
}
// 在此补充代码
show.start()
show.stop()
</script>
</body>

</html>


写回答

2回答

好帮手慕慕子

2022-01-04

同学你好,代码效果实现是对的,建议优化:直接在点击开始按钮时,判断是否存在定时器,存在的话先清除,然后再开启定时器就可以了,简化代码,如下:

https://img.mukewang.com/climg/61d3ad7309fcd36d08570514.jpg

祝学习愉快~

0

听的说

提问者

2022-01-03

<!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 show = {
content: "Hello World ",
timer: null,
lock: true,
start: function() {
// 在此补充代码
startBtn.addEventListener('click', () => {
if (!this.lock) return;
clearInterval(this.timer);
this.timer = setInterval(() => {
box.innerHTML += "<span>" + this.content + "</span>";
}, 1000);
this.lock = false;
setTimeout(() => {
this.lock = true;
console.log(this.lock);
}, 2000)
}, false);
},
stop: function() {
// 在此补充代码
stopBtn.addEventListener('click', () => {
clearInterval(this.timer);
}, false);
},
}
// 在此补充代码
show.start()
show.stop()
</script>
</body>

</html>

截流问题解决了 老师帮我看看代码也没有优化空间或者bug

0

前端工程师

前端入门如同写字,如果你不知道从哪开始,那就选择前端(含Vue3.x,React17,TS)

20327 学习 · 17877 问题

查看课程