为什么这个clearInterval不起作用?

时间:2015-10-10 07:22:15

标签: javascript

我正在进行一场比赛,其中两个图像向右移动一个随机数的px,但它们不会以清除间隔停止,警报“停止”工作。我正在使用红色和绿色的图片来改变z-index,就像一个用于启动和停止比赛的红绿灯。

<script type="text/javascript">

var ship = 0;
var ufo = 0;

function random()
{

    var rand = Math.floor((Math.random() * 15) + 1);
    var rand2 = Math.floor((Math.random() * 15) + 1);

    ship = ship + rand;
    ufo = ufo + rand2;

    document.getElementById("ufo").style.left = ufo + 'px';
    document.getElementById("spaceship").style.left = ship + 'px';


}

function start()
{
    if(document.getElementById("red").style.zIndex == 1)
    {
        document.getElementById("red").style.zIndex = "0";
        alert("go");
        var timer = setInterval(function() {random()},1000);    

    }
    else
    {
        document.getElementById("green").style.zIndex = "0";
        document.getElementById("red").style.zIndex = "1";
        clearInterval(timer);
        alert("stop");


    }

}

</script>

1 个答案:

答案 0 :(得分:1)

因为var timer只存在于if语句中。您需要将其移到start()函数之外,如下所示:

var timer;

function start()
{
    if(document.getElementById("red").style.zIndex == 1)
    {
        document.getElementById("red").style.zIndex = "0";
        alert("go");
        timer = setInterval(function() {random()},1000);    
    }
    else
    {
        document.getElementById("green").style.zIndex = "0";
        document.getElementById("red").style.zIndex = "1";
        clearInterval(timer);
        alert("stop");
    }
}