1.连续点击开始(阻止执行速度 加速)
节流闸变量定义true
节流闸 : 当执行vue方法时,将节流闸赋值为false ,然后对节流闸进行判断当节流闸为false时就 return
2.Vue this访问
this可以访问data中属性,也可以访问methods中定义方法
代码:
<template>
<div>
<!-- 需求1: 点击开始, 每隔 200ms 随机切换页面上显示的名字 -->
<!-- 需求2: 点击结束, 停下 -->
<!-- 需求3: 多次点击开始, 不会加速 -->
<!-- 需求4: 点击开始, 若没点结束, 8 秒后自动结束 -->
<!-- 需求5: 点击开始, 切换速度非常非常快, 间隔时间改为 10ms, 点击结束, 慢慢减速, 3 秒后彻底停下 -->
<h2>随机点名</h2>
<div class="box">
<span>名字是:</span>
<div class="qs">{{ showName }}</div>
</div>
<div class="btns">
<button @click="start" class="start">开始</button>
<button @click="stop" class="end">结束</button>
</div>
</div>
</template>
<script>
// 避免对全局作用域产生过多的污染, 不建议将多个函数要用到的变量写在全局, 而是放在 data 中
// let timerId
export default {
data() {
return {
names: [
'张三',
'张四',
'张五',
'张六',
'张七',
'张八',
],
showName: '这里显示姓名',
timerId: '',
flag: true,
time: 10
}
},
methods: {
start() {
// 1. 给按钮绑定点击事件
// 2. 点击后开启一个间歇定时器
// 这里传入回调函数一定要用箭头函数
// 为什么? 如果是普通函数, this 指向 window 对象
// 解决方案1: 清除后开启, 后果: 如果手速够快, 就会卡着不动
// 解决方案2: 开定时器后禁用按钮, 点击结束才放开按钮
// 解决方案3: 使用一个节流阀来控制
// 初次进来是 true, 不会阻拦
if (!this.flag) return
// 马上改为 false, 关闭这个阀门
this.flag = false
// clearInterval(this.timerId)
const fn = () => {
// console.log(this.names)
// 随机数
// random() 生成 0 ~ 1 的随机数, 左闭右开
const random = parseInt(Math.random() * this.names.length)
// console.log(random)
// 3. 随机修改页面上显示的名字
this.showName = this.names[random]
// 做完任务后, 再开启定时器
this.timerId = setTimeout(fn, this.time)
}
this.timerId = setTimeout(fn, this.time)
// 同时开启一个延时定时器, 8 秒后清除上面的定时器
setTimeout(() => {
// this. 除了可以访问 data 中的属性, 也可以访问 methods 中定义的方法
this.stop()
}, 8000)
},
stop() {
// 迷惑用户的, 让速度变慢
let slowId = setInterval(() => {
this.time += 20
}, 200)
// 这里是直接停下
setTimeout(() => {
this.flag = true
clearInterval(this.timerId)
// 彻底停下时, 还需要清除刚刚开启的修改 time 的定时器
clearInterval(slowId)
// 还需要将 time 还原成 10
this.time = 10
}, 3000)
}
}
}
</script>
<style>
* {
margin: 0;
padding: 0;
}
h2 {
text-align: center;
}
.box {
width: 600px;
margin: 50px auto;
display: flex;
font-size: 25px;
line-height: 40px;
}
.qs {
width: 450px;
height: 40px;
color: red;
}
.btns {
text-align: center;
}
.btns button {
width: 120px;
height: 35px;
margin: 0 50px;
}
</style>