老师我代码有bug 请老师协助下

来源:3-13 编程练习

菜鸟瑞

2021-05-08 17:24:11

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title>Document</title>

    <style>

        div {

            width300px;

            margin20px 0;

            line-height30px;

            backgroundyellowgreen;

        }

    </style>

</head>

<body>

    <button id="start">开始</button>

    <button id="stop">停止</button>

    <button id="clear">重置</button>


    <div id="box"></div>

    <script>

        const startBtn = document.getElementById('start')

        const stopBtn = document.getElementById('stop')

        const box = document.getElementById('box')

        const clear = document.getElementById('clear')


        var show = {

            content: "\tHello World",

            timer: null,

            start: function () {

                // 在此补充代码

                startBtn.addEventListener('click',()=>{

                    this.timer=setInterval(() => {

                        box.innerText+=this.content

                        console.log(startBtn);

                    }, 1000);

                },false)

            },

            stop: function () {

                // 在此补充代码

                stopBtn.addEventListener('click',()=>{

                    clearInterval(this.timer)

                },false)

            },

            clearText:function(){

                clear.addEventListener('click',()=>{

                    box.innerText=''

                },false)

            }

        }

         // 在此补充代码

         show.start();

         show.stop();

         show.clearText();

    </script>

</body>

</html>

问题描述:

老师我这段代码多次点击之后 出现bug   是否要添加节流锁

写回答

1回答

好帮手慕久久

2021-05-08

同学你好,代码中,每点击一次“开始”按钮,就会开启一个定时器,由于定时器累加,导致效果不对:

http://img.mukewang.com/climg/60965a80090039a406190147.jpg

可以添加节流锁,调整如下:

http://img.mukewang.com/climg/60965b5c09cd17da08490852.jpg

或者可以在点击开始按钮时,将定时器先清除再开启:

http://img.mukewang.com/climg/60965bc309e3abde08280884.jpg

祝学习愉快!

0

0 学习 · 15276 问题

查看课程