请老师检查代码,另外请教一下怎么实现函数节流

来源:3-13 编程练习

子衿设计

2022-03-10 18:23:50

<!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,
            start: function () {
                // 在此补充代码
                // 如何实现函数节流?
                // clearInterval(timer);
                startBtn.addEventListener('click', () => {
                    timer = setInterval(() => {
                        // console.log(this);
                        box.innerHTML += this.content;
                    }, 1000);
                }, false);
            },
            stop: function () {
                // 在此补充代码
                stopBtn.addEventListener('click', () => {
                    clearInterval(timer);
                }, false);
            },
        }
        // 在此补充代码
        show.start();
        show.stop();
    </script>
</body>

</html>


写回答

1回答

好帮手慕久久

2022-03-10

同学你好,代码有如下问题:

1、建议在Hello World之间添加上空格,这样与效果图更符合:

https://img.mukewang.com/climg/6229d23d0982ed8906570173.jpg

2、快速多次点击“开始”按钮,定时器速度越来越快。建议多次点击时,先清掉可能存在的定时器,再开启新的:

https://img.mukewang.com/climg/6229d33909076b7c09580725.jpg

这里不涉及到函数节流,只涉及到定时器开关。

祝学习愉快!

0

0 学习 · 17877 问题

查看课程