sraban
sraban

Reputation: 121

Simultaneous function call in javascript

here is the code:

var ctx    = canvas.getContext('2d');
var chop1   = new Image();
chop1.src = "img/chopper.png";
var blt = new Image();
blt.src = "img/bullet.png"
var chopperX = 0;
var chopperY = 0;
var ascent = 2;
var limit = 500;
var start = null;
var bltX = 135;

function fire()
{
 bltX +=ascent;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(blt,bltX,20 , 
chop1.width, chop1.height);
requestAnimationFrame(fire);


}


function up(){
    chopperY-=ascent;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(chop1,0,chopperY , 
              chop1.width, chop1.height);

    requestAnimationFrame(up);

if(chopperY == 20){
    setInterval(fire,1000)



}
if(chopperY == 0){

   fly();
}
 }

function fly() {
chopperY+=ascent;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(chop1,0,chopperY , 
              chop1.width, chop1.height);
if (chopperY < limit) {
    requestAnimationFrame(fly);
}
if(chopperY==limit){

   up();
}
fly();

As per the condition(chopperY == 20),"fire" method is excute.But i want to call "fire" and "fly" function simultaneously at this particular condition. Is there any way to do this? In this code when "fire" method excute then "fly" method stop automatically.Is there any way to solve this issue?

Upvotes: 0

Views: 135

Answers (2)

basilikum
basilikum

Reputation: 10528

I'm not sure if I understand you correctly but if your goal is, to pass two functions to setInterval, than you can achieve this by wrapping them up in an anonymous function:

if(chopperY == 20){
    setInterval(function () {
        fire();
        fly();
    },1000)
}

This will call both functions every second. However, the fire function will get executed first.

Upvotes: 0

Eccountable
Eccountable

Reputation: 642

It looks like you are making a game. You should use event listeners. See some examples here or keyboard examples. This would allow you to connect keyboard actions to code and they should run at the same time.

Upvotes: 1

Related Questions