Javascript setTimeout clearTimeout问题

时间:2011-09-16 21:55:30

标签: javascript settimeout

我有一个我想要放在一起的样本,我需要在完成后清除Timeout,单击按钮但只运行一次,我想清除超时并能够再次单击它通过这个过程。

以下是下面列出的代码

<!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>

1 个答案:

答案 0 :(得分:0)

没有测试过这个,但是给它一个旋转:

<!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>