Skip to content
Advertisement

Setting interval only once by an event listener, but run other functions every time

See this code:

function handleTouchStart(event) {
       event.preventDefault();
       cnvs.removeEventListener("touchstart", handleTouchStart);
       var x1 = event.touches[0].clientX-cnvs.offsetLeft;
       callerOfCNVSTouchStart = setInterval(function () {
         if (x1 > cnvs.width/2  && whiteShip.x2 < cnvs.width) {
          whiteShip.x1+= 3;
         } else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
          whiteShip.x1-= 3;
         }
        }, 20);
        nBMC = setInterval(makeNewBullets,200);
        setInterval(sendEnemies,2000);//I want to run this line only once 
}

I want the other functions to run every time the event occurs, but set the interval for sendEnemies only once. How can I do that?

Advertisement

Answer

Use a variable like var sentEnemies = false; outside function handleTouchStart and update it in the function to true the first time and use if(!sentEnemies) for the line to execute only once.

var sentEnemies = false;

function handleTouchStart(event) {
       event.preventDefault();
       cnvs.removeEventListener("touchstart", handleTouchStart);
       var x1 = event.touches[0].clientX-cnvs.offsetLeft;
       callerOfCNVSTouchStart = setInterval(function () {
         if (x1 > cnvs.width/2  && whiteShip.x2 < cnvs.width) {
          whiteShip.x1+= 3;
         } else if (x1 < cnvs.width/2 && whiteShip.x1 > 0) {
          whiteShip.x1-= 3;
         }
        }, 20);
        nBMC = setInterval(makeNewBullets,200);

        if (!sentEnemies) {
           setInterval(sendEnemies,2000); // Will execute only once
           sentEnemies = true;
        }
        
}
8 People found this is helpful
Advertisement