为什么我的定时器消除不了

来源:3-13 编程练习

好学生慕小帅

2022-07-30 10:05:01

<!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 () {
                start.addEventListener(
                    'click',
                    () => {
                        var time = setInterval(() => {
                            box.innerHTML += this.content + ' ';
                        },1000)
                    }
                )
            },
            stop: function () {
                stop.onclick = function() {
                    clearInterval(time);
                }
            },
        }
        show.start();
        show.stop();
    </script>
</body>

</html>


写回答

1回答

好帮手慕久久

2022-07-30

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

1、当元素有id时,可以直接利用id操作元素,而不用获取元素,比如:

https://img.mukewang.com/climg/62e495b909e3253204790157.jpg

但是这样写,会存在未知的问题。比如同学的代码中,没有用变量startBtn、stopBtn绑定事件,效果就受到了影响。

调整如下:

https://img.mukewang.com/climg/62e4960b09f100d805030213.jpg


https://img.mukewang.com/climg/62e496130974c9f004960152.jpg

2、开始按钮中,声明的定时器变量time,是局部变量:

https://img.mukewang.com/climg/62e496310941d79905500198.jpg

它不能在结束按钮的事件处理函数中使用,所以无法清除定时器。

修改如下:

https://img.mukewang.com/climg/62e496e40981252209060677.jpg

祝学习愉快!

0

0 学习 · 17877 问题

查看课程