为什么我已经设表先关了,但是图片变化还是越来越快

来源:5-1 定时器和延时器(1)

weixin_慕村1291783

2020-11-11 12:44:12

# 具体遇到的问题

# 报错信息的截图

# 相关课程内容截图

# 尝试过的解决思路和结果

# 粘贴全部相关代码,切记添加代码注释(请勿截图)

<!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>        img {            height120px;        }    </style></head>
<body>    <div id="box"></div>    <script>        // 建一个红绿灯类

        function HongLv() {            this.color = 1;            this.init();            this.bingEvent();        }        var box = document.getElementById('box');        HongLv.prototype.init = function() {            this.dom = document.createElement('img');            this.dom.src = 'images/' + this.color + '.jpg';            box.appendChild(this.dom)        }        HongLv.prototype.bingEvent = function() {            var self = this;            this.dom.onload = function() {                var timer;                clearInterval(timer);                timer = setInterval(function() {                    self.color = parseInt(Math.random() * (4 - 1+ 1);
                    // if (self.color == 4) {                    //     self.color = 1;                    // }                    self.huan();                }, 1000)
            }        }        HongLv.prototype.huan = function() {            this.dom.src = 'images/' + this.color + '.jpg';        }        var count = 50;        while (count--) {            new HongLv();        }
        function suiji(ab) {
        }    </script></body>
</html>

写回答

2回答

好帮手慕星星

2020-11-12

同学你好,在onload事件中声明timer变量,那么每调用一次bingEvent方法,timer就会声明一次。而clearInterval清除的是新声明的,并不是上一次,所以定时器会叠加,变化越来越快。


好帮手慕’老师的意思是通过this作为属性,都通过this.timer进行定时器操作,就不会叠加了。

祝学习愉快!

0

好帮手慕慕子

2020-11-11

同学你好,因为在onload事件中使用使用var声明timer,导致每次图片加载成功之后快就会重新声明一次,所以无法实现效果。

建议修改:将timer添加到this上

http://img.mukewang.com/climg/5fab7ebd09f913a903950186.jpg

然后通过this.timer进行操作,先判断是否有定时器,有的话再清除

http://img.mukewang.com/climg/5fab7eed09d1715408310507.jpg

祝学习愉快~

0
heixin_慕村1291783
h 没太理解 为什么在onload里面一直声明 有什么影响
h020-11-12
共1条回复

0 学习 · 15276 问题

查看课程