繁体   English   中英

Javascript setTimeout clearTimeout问题

[英]Javascript setTimeout clearTimeout issue

我有一个示例示例,尝试将其放在一起,完成后需要清除超时,单击按钮但只能运行一次,我想清除超时并能够再次单击以遍历处理。

这是下面列出的代码

<!DOCTYPE html>
<html>
    <head>
        <title>Animate Files</title>
        <script type="text/javascript">
            var img0 = new Image( 640, 960);
            img0.src="img/Mouth-m.jpg";

            var img1 = new Image( 640, 960);
            img1.src="img/Mouth-o.jpg";

            var img2 = new Image( 640, 960);
            img2.src="img/Mouth-s.jpg";

            var img3 = new Image( 640, 960);
            img3.src="img/Mouth-e.jpg";

            var img4 = new Image( 640, 960);
            img4.src="img/Mouth-m.jpg";

            var i = 0;
            var nbImg = 3;

            function animate() {
                document.images[0].src = eval("img" + i).src;
                i++;
                if(i == nbImg) i=4; 
                junk = setTimeout("animate();", 300);
            }
        </script>
    </head>
    <body>
        <img src="img/Mouth-m.jpg" width="640" height="960"/>
        <button type="button" onclick="animate()">One</button>
    </body>
</html>

尚未测试过,但请尝试一下:

<!DOCTYPE html>
<html>
<head>
<title>Animate Files</title>
<script type="text/javascript">
    var img0 = new Image( 640, 960);
    img0.src="img/Mouth-m.jpg";

    var img1 = new Image( 640, 960);
    img1.src="img/Mouth-o.jpg";

    var img2 = new Image( 640, 960);
    img2.src="img/Mouth-s.jpg";

    var img3 = new Image( 640, 960);
    img3.src="img/Mouth-e.jpg";

    var img4 = new Image( 640, 960);
    img4.src="img/Mouth-m.jpg";

    var hiatus;

    function animate(i) {
        clearTimeout(hiatus);

        document.images[0].src = window['img' + i].src;

        if(i === 4) {
            return;
        }

        hiatus = setTimeout(function() {
            animate(i + 1);
        }, 300);
    }
</script>
</head>
<body>
    <img src="img/Mouth-m.jpg" width="640" height="960"/>
    <button type="button" onclick="animate(0)">One</button>
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM