关于锁lock的问题
来源:3-13 编程练习
雨7758978
2021-11-11 18:42:18
相关代码:
<!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:1,//打开状态 start: function () { if(this.lock==1){ this.lock=0; startBtn.addEventListener('click',()=>{ this.timer=setInterval(()=>{ box.innerHTML+=' '+'Hello World'; },1000); },false) } }, stop: function () { // 在此补充代码 stopBtn.addEventListener('click',()=>{ clearInterval(this.timer); this.lock=1; },false) }, } // 在此补充代码 show.start(); show.stop(); </script> </body> </html>
问题描述:
为什么在start函数中把if判断语句放在内部就好用
相关截图:
好用!
还是会出现连续点击有bug。
1回答
好帮手慕久久
2021-11-12
同学你好,解答如下:
如下这样写:
当 show.start()执行时,就会执行该if语句,而点击按钮时,并不会再次执行if语句:
点击事件触发时,只会执行事件处理函数中的代码:
即lock相关代码不会再次执行,因此起不到锁的作用。
需要把if语句写在事件处理函数中:
这样点击事件触发中,才会执行lock的相关的判断。
祝学习愉快!
相似问题