简体   繁体   中英

I'm trying to call a method in a constructer every second for 15 seconds but setInterval doesn't seem to work

The code - also available here :

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000000" ;
ctx.fillRect(0,0,600,600);
ctx.fillStyle ="#ffffff";

var entities = [];
var x;
var y;

function ship(x, y) {
  entities.push(entities.length-1);
  this.name = entities.length-1;
  this.draw = function(){
    ctx.fillRect(x,y,30,30);
  };

  this.update = function(){
    x+=10;
    this.draw();
  }; 
}

var bob = new ship(0,0);
bob.draw();

var intervalID = setInterval(bob.update(), 1000);
setTimeout(function() {
  clearInterval(intervalID);
}, 18000);

Basically, I draw a square on the top left corner. I then am trying to use a method to move it in real time. When I used a for loop, I can see that the square moved, but it obviously moves too fast to even notice.

Change line 48 in index.html to

 var intervalID = setInterval(function(){bob.update()}, 1000);

and you should be good.

您需要将绑定引用传递给bob.update

var intervalID = setInterval(bob.update.bind(bob), 1000);

I've not run the code, but this looks to be your problem

setInterval(bob.update(), 1000)

The first argument of setInterval needs to be a function object - in this case, the update function of the ship object.

In the above statement, you are actually calling the update function, so what's being passed to setInterval is not the update function itself, but the returned value from calling it - which is undefined - so your setInterval does.. nothing, each second.

You'll need to 'bind' the update function to the bob object, so that the value of this when it is actually invoked on each interval is the this of the bob object.

Change it to this, ie passing the update function bound to the bob object, and try running it again

setInterval(bob.update.bind(bob), 1000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM