so I am making a 2d canvas game in Javascript and I want the enemy mobs to shoot a bullet every let's say 3 seconds. I'm almost done with the code , i made everything i just don't know how to make the function repeat.

//this is the enemy object
 function Enemy(x, y){
 this.sprite = enemySprite;
 this.x = x;
 this.y = y;
 this.shooting = function(){
    while(enemyBullets <= bulletsPerTick){
        var enemybullet = new enemyBullet(this.x , this.y);
        enemyBullets.push(enemybullet);//i'm adding the bullet object to an array .
    for(var i = 0; i<enemyBullets.length;i++){
        enemyBullets[i].move();//if there is an element in the array , draw and update the bullet.
}// i left only the important elements of the object needed to answer my question
    //this is the enemy bullet object
    function enemyBullet(x, y) {
    this.x1 = x;
    this.y1 = y;
   this.r = 5;
    this.show = function () 
    ctx.arc(this.x1, this.y1, this.r, 0, Math.PI * 2);
    ctx.fillStyle = "black";
    ctx.closePath()//drawing the bullet
this.move = function () {
    this.x1 = this.x1 - 5;//updating the bullet

In my main file , i have a function draw() which is in requestAnimationFrame(draw):

for (var j = 0; j < enemies.length; j++) {
            enemies[j].show();//here i spawn the enemy sprite
            enemies[j].shooting();//this is the function which adds the bullets to the array , draws them and updates them.

Basically , when i press the start the program now , only one bullet flies and disappears and i want that process to continue over and over again every few seconds , let's say 3 seconds for example , i tried to add enemies[j].shooting() in an interval and timeout but they are in draw, which is in requestAnimationFrame and it doesn't seem to work , if anyone have any clue how to help me I want every advice possible. Also if you need more information about the problem , let me know.


Are you looking for something like setInterval? That would be a very JavaScript-ish way to make a repeating task.

If you want something based on a per-frame basis you'd probably want to have some manual counters increased based on a deltaTime of some sort and reset at some threshold, but I think setInterval would be sufficient for your case. Don't forget to keep the intervalID returned from setInterval so you can clearInterval when your enemy dies.

Would something like that help?

  • \$\begingroup\$ I tried with setInterval , but it doesn't seem to work , maybe Because it is in a request animation frame function , which updates it very fast \$\endgroup\$ Oct 30 '19 at 15:06
  • \$\begingroup\$ i figured it out by myself , i used SetInterval and it worked , thanks for your anwer. \$\endgroup\$ Oct 30 '19 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.