0

The problem is that my function executes only once after using setInverval(). Anyone knows how to fix it so update() method of the snake object actually runs over and over again?

Here is the code:

let canvas = document.getElementById("cnvs");
ctx = canvas.getContext("2d");

canvas.width=500;
canvas.height=500;

ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);

let step = canvas.width / 15;


let snake = new Snake(1);
console.log(snake);
setInterval(snake.update(),1000);
setInterval(snake.draw(),1000);




    function Snake(dir) {
    this.x = 300;
    this.y = 300;
    this.dir = dir;
    this.step=step;
    this.update = function () {
        if (this.dir === 1) {
            console.log(this.y);
            this.y-=this.step;
            console.log(this.y);
        }
        else if (this.dir === 2) {
            this.x+=this.step;
        }
        else if (this.dir === 3) {
            this.y+=this.step;
        }
        else if (this.dir === 4) {
            this.x-=this.step;
        }
   }

    this.draw = function () {
        ctx.fillStyle = "red";
        ctx.fillRect(this.x,this.y,step,step);
    }
   }
AJlearn
  • 5
  • 1
  • if calling `snake.update()` returned a function that you wanted to use with setInterval, this would work. But it doesn't, and you want to use snake.update itself with setInterval. So - `setInterval(snake.update, 1000)` eg – James Dec 06 '17 at 22:27
  • 1
    @James That won't work since snake.update uses this. `setInterval(snake.update.bind(snake), 1000)` would work. – Paul Dec 06 '17 at 22:29
  • Not working. When I use `setInterval(snake.update, 1000, snake)` or `setInterval(snake.update, 1000)` nothing happens. – AJlearn Dec 06 '17 at 22:32
  • @AJlearn Use `setInterval(snake.update.bind(snake), 1000)`. – Paul Dec 06 '17 at 22:33
  • You're right @Paulpro. – James Dec 06 '17 at 22:34
  • @Paulpro It works! Thank you. – AJlearn Dec 06 '17 at 22:35

0 Answers0