JavaScript 间歇函数在点击事件内的多次生成bug解决方法

 我们在不停的点击开始按钮  每点击一次就会产生一个定时器 多个定时器就会叠加在一起 速度变快

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <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>
</head>
<body>
    <h2>随机点名</h2>
    <div class="box">
        <span>名字是:</span>
        <div class="qs">这里显示姓名</div>
    </div>
    <div class="btns">
        <button class="start">开始</button>
        <button class="end">结束</button>
    </div>
    <script src="./js/index.js"></script>
    <script>
        const arr = ['马超', '黄忠', '赵云', '关羽', '张飞']
        const start = document.querySelector('.start')
        const qs = document.querySelector('.qs')
        let id 
        let i
        start.onclick = function () {
             // bug :我们在不停的点击开始按钮  每点击一次就会产生一个定时器 多个定时器就会叠加在一起 速度变快
            //  解决方法: 点击一次就清除一次相应生成的定时器 不管用户点击多少次 仅仅只产生一个定时器
            if (id) {
                clearInterval(id)
            }
            id = setInterval(function () {
                i = getRandom(0, arr.length - 1)
                qs.innerHTML = arr[i]
            }, 30)
            if (arr.length === 1) {
                start.disabled = true
                end.disabled = true
            }
        }
        const end = document.querySelector('.end')
        end.onclick = function () {
            clearInterval(id)
            arr.splice(i, 1)
        }
    </script>
</body>

</html>

解决方法:点击一次就清除一次相应生成的定时器 不管用户点击多少次 仅仅只产生一个定时器 代码参考上方

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值