请老师检查
来源:3-13 编程练习
tobeabee
2023-01-29 02:25:02
<!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,
locked: false,//节流锁
start: function () {
// 在此补充代码
// console.log(self);
startBtn.onclick = () => {
if (this.locked) {
return;
}
locked = true;
clearInterval(this.timer);
this.timer = setInterval(() => {
box.innerText += this.content;
}, 1000);
setTimeout(() => {
locked = false;
}, 1000);
}
},
stop: function () {
// 在此补充代码
stopBtn.onclick = () => {
if (this.locked) {
return;
}
locked = true;
clearInterval(this.timer);
setTimeout(() => {
locked = false;
}, 1000);
}
}
}
// 在此补充代码
show.start();
show.stop();
</script>
</body>
</html>当我连续点击“开始”按钮的时候并不会出现新的helloworld,得等到我不继续点击之后才会,我设置了节流锁,在第一次点击时形成的定时器为什么不起作用?
另一个问题是:节流锁和“设表先关”是只需要其中一个吗,还是说最好两个都有?
1回答
同学你好,问题解答如下:
1、点击开始按钮时设置的锁,与if判断中的锁,不是同一个,所以锁没有作用:


2、代码中,并没有修改this.locked的值,this.locked的值始终是false,所以连续点击时,始终会先清除定时器:

即之前开启的定时器会被清掉,所以连续点击时,不会出现新的hello world。
代码修改如下:

3、节流锁和“设表先关”这两个手段没有必然联系,要根据具体需求选用。“设表先关”只是针对定时器的,代码中需不需要定时器也不是固定的。要根据逻辑,判断用什么手段。
祝学习愉快!
相似问题