Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 两个设定的间隔构成无限循环_Javascript_Canvas_Dom Events - Fatal编程技术网

Javascript 两个设定的间隔构成无限循环

Javascript 两个设定的间隔构成无限循环,javascript,canvas,dom-events,Javascript,Canvas,Dom Events,我正在做一个简单的游戏,我想用setInterval移动两个对象(一个杯子的两个图像)。 在所有函数调用之后,它会将图片绘制到另一个位置,使其看起来像是在移动。如果我只使用一次setInterval,没有问题,但是如果我使用两次,它将进入一个无限循环。你能帮帮我吗,它为什么要这样做 window.onload = main; var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d");

我正在做一个简单的游戏,我想用
setInterval
移动两个对象(一个杯子的两个图像)。 在所有函数调用之后,它会将图片绘制到另一个位置,使其看起来像是在移动。如果我只使用一次
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);
    }
}

使用两种不同的计时器:

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

这可能是因为您在第二次启动“计时器”之前未清除“计时器”

您已覆盖计时器。因此,clearInterval仅清除第二个setInterval。请先清除第一个setInterval,或使用其他变量名。如何才能先清除第一个setInterval?我想当我第一次使用setInterval时,它会自动清除,因为它在move_1_2中,然后是第二个setInterval。如果我不知道,我的timerId的名字是什么,我该如何使用clearInterval呢?(在move_1_2函数中,我不知道哪个是我的id)。现在它只移动一次,但我使用了setInterval twices,因为我想移动它两次。你需要从第一个计时器调用第二个计时器。@user3115593我想你不懂setInterval。