-2

I have a setInterval that draws my snake game, and everytime the snake "eats" I have a clearInterval and then the setInterval var with adjusted speed. The original setInterval starts on load. How can I make it start with the press of a button?

My attempts at placing the setInterval inside the button and using functions have worked in making the button start the setInterval, but it always breaks my clearInterval inside the draw function.

<button onclick="">Start game</button>

if (snakeX == food.x && snakeY == food.y){
            food = {
                x : Math.round(Math.random()*(cvsWidth/snakeWidth-1)),
                y : Math.round(Math.random()*(cvsHeight/snakeHeight-1))
            };
            score++;
            if (speed >= 40) speed = speed-3;
            clearInterval(interval);
            interval = setInterval(draw, speed);
        }else{

            //Remove last
            snake.pop();
        }

var speed = 140;

var interval = setInterval(draw, speed);
Meepy
  • 41
  • 5
  • your button doesn't do anything. [mcve] please. – apple apple May 02 '19 at 07:55
  • I know that, I have left it empty because I can't figure out what to put there. I'm wondering what to do with it. – Meepy May 02 '19 at 07:56
  • What exactly is inside your `draw` function? If it's everything that is above - you're redeclaring speed and interval each time it's called. – Walk May 02 '19 at 07:59
  • Yeah, I've been using it to speed up the snake by changing the setInterval. Didn't think it would be necessary to add more than this code, and not putting something inside button since I didn't want to over complicate it since I suspected it really was quite simple. I am very new at this – Meepy May 02 '19 at 08:07

1 Answers1

-1

By setting the onclick attribute of your button to start() causes start to be called when you click the button.

I also declare interval as a global variable since I think you need it to be global.

Then when start gets called then the interval gets started and the id of the interval is put into interval

var speed = 500;

function draw() {
  console.log("Running")
}


var interval;
function start() {
  //Prevent start from running twice.
  if(interval != null) return;
  interval = setInterval(draw, speed);

}
<button onclick="start()">Start game</button>
Wendelin
  • 2,354
  • 1
  • 11
  • 28