关于添加节流锁

来源:3-13 编程练习

龙同學

2021-04-16 14:52:38

相关代码:

<!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.lock = false;
this.timer = setInterval(() => {
box.innerHTML += this.content + ' ';
}, 1000)
setTimeout(() => {
this.lock = true;
}, 1000);
}, false)
},
stop: function () {
stopBtn.addEventListener('click', () => {
clearInterval(this.timer);
}, false)
}
}
show.start();
show.stop();
</script>
</body>

</html>

问题描述:

老师,为什么添加了节流锁没效果?

写回答

1回答

好帮手慕慕子

2021-04-16

同学你好,应该是在点击事件后将lock值设置为false,这样连续多次点击按钮就不会一致执行里面的代码了,在一秒后将内容追加到页面中,再将lock的值调整为true,这样再次点击的时候就会再次触发里面的代码。

http://img.mukewang.com/climg/60793ad109c6340908600484.jpg

但是添加节流锁只能保证在一定时间内点击按钮不会执行对应的代码,但是连续多次点击还是会开启多个定时器,导致效果不对。所以这里不需要考虑多次点击的情况,重点是学习与掌握箭头函数的使用

祝学习愉快~

0

0 学习 · 15276 问题

查看课程