请老师检查一下作业

来源:3-13 编程练习

激情的樱木花道

2021-07-01 08:36:52

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <title>Document</title>

    <style>

        div {

            width300px;

            margin20px 0;

            line-height30px;

            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')

        let  timers;

        var show = {

            content: "Hello World",

            timer: null,

            startfunction () {

               startBtn.onclick=()=>{

                   timers=setInterval(()=>{

                    box.innerHTML+=`${this.content} `;

                   },1000)

               }

            },

            stopfunction () {

                stopBtn.onclick=function(){

                    clearInterval(timers);

                }     

            },

        }

        show.start();

        show.stop();

    </script>

</body>

</html>


写回答

1回答

好帮手慕久久

2021-07-01

同学你好,代码没有语法错误,只是存在一个小bug。当多次点击“开始”按钮时,div#box中的内容出现的速度会加快:

http://img.mukewang.com/climg/60dd23760a0b01ac05830206.jpg

原因是每点击一次“开始”按钮,就会开启一个定时器。定时器叠加,就会造成div#box中的内容出现的速度增快。

建议点击开始按钮之前,将之前的定时器清掉:

http://img.mukewang.com/climg/60dd23d30941e55506280354.jpg

另外,代码可以优化一下:

对象show中,已经定义了timer,可以用它来存储定时器,不用在全局中再次定义变量timers:

http://img.mukewang.com/climg/60dd24e309def8be07330774.jpg

祝学习愉快!

1

0 学习 · 15276 问题

查看课程