两组间隔使无限循环

时间:2013-12-18 16:52:09

标签: javascript canvas javascript-events

我正在做一个简单的游戏,我想用setInterval移动2个对象(一个杯子的两个图像)。 在所有函数调用之后,它会将图片绘制到另一个地方,使其看起来像是在移动。如果我只使用setInterval一次,没有问题,但如果我使用它两次,它会进入无限循环。你能帮帮我吗,为什么要这样做?

window.onload = main;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

function main(){
backGround.src = "pic1";
backGround.onload = function(){
    ballImg.src = "pic2";
    ballImg.onload = function (){
        cupImg.src = "pic3";
        cupImg.onload = function(){

            startGame();

        };
    };
};

}

function startGame(){
context.clearRect(0, 0, w, h);
context.drawImage(backGround, 0, 0, w, h);
context.fillText("START!",50,50);
canvas.addEventListener('click',jonas, false);

}

function jonas(){
timer = setInterval(move_1_2, timeStep); //there is no problem if i use it once, but I would like to do it more time
timer = setInterval(move_1_2, timeStep); //If use it like this, it goes into an infinite loop

}

function move_1_2 () {

posX =((posX2-posX1)/density)*i;
bposX =(bposX2-bposX1)/density*i;
context.clearRect(0, 0, w, h);
context.drawImage(backGround, 0, 0, w, h);
context.drawImage(cupImg, posX1 + posX, posY, cupw, cuph); //I draw 3 cups, the two at the sides are moving
context.drawImage(cupImg, posX3, posY, cupw, cuph);
context.drawImage(cupImg, posX2 - posX, posY, cupw, cuph);

if (++i == density){
    i = 0;
    clearInterval(timer);
}

}

1 个答案:

答案 0 :(得分:0)

使用两个不同的计时器:

timerA = setInterval(move_1_2, timeStep);
timerB = setInterval(move_1_2, timeStep); 

这可能是因为你没有在第二次启动它之前清除“计时器”