jeudi 1 janvier 2015

Why does my code in setTimeout not work in JavaScript?


Vote count:

0




My method, Chomp.prototype.animate does not work properly. My code works when the function does not apply Chomp.prototype.playerMove.


When Chomp.prototype.playerMove is applied, then the if statement involving counter before the addEventListener can sometimes execute the addEventListener, even if counter is greater than one, those times it executes the function in addEventListener many times, depending on how long the code was running before it was executed. Those times, it should not have executed the addEventListener, and if it did, then counter should be added to more than one, and then not executed again. Counter was added to more than one, even on these times of the addEventListener being executed multiple times.


Even stranger, when I have Chomp.prototype.animate always set counter to 1 instead of 0, it will still execute the if statement that says if (counter < 1) once. Also, when Chomp.prototype.playerMove is applied, then Chomp.prototype.chomping does not work quite right. (It does work without Chomp.prototype.playerMove). This is very strange, and I do not understand the problem.


If there is request for a certain part of my code, then I could post that, but my full code is probably not all useful to the question.



var counter = 0;
var rotation;
var Chomp = function(x, y) {
/*many properties*/
}
Chomp.prototype.chomping = function() {
/*properties and conditions, etc.*/
}
Chomp.prototype.animate = function() {
var that = this;
Chomp.prototype.chomping.apply(this);
Chomp.prototype.playerMove.apply(this);
//counter = 1;
counter = 0;
setTimeout(function(){
Chomp.prototype.animate.apply(that);
}, 100);
}
Chomp.prototype.playerMove = function() {
var that = this;
/*values*/
var yNew = 0, xNew = 0, rotate = "";
var once = function(event) {
/*conditions for keys, etc.*/
Chomp.prototype.move.call(that, xNew, yNew, rotate);
/*values*/
removeEventListener("keydown", once);
}
if (counter < 1)
addEventListener("keydown", once);
/*more code*/
}
Chomp.prototype.move = function(xNew, yNew, rotate) {
var that = this;
counter += 1;
/*loops, conditions, etc.*/
var yellow = new Chomp(30, 60);
Chomp.prototype.animate.apply(yellow);


Thanks ahead of time! :)



asked 1 min ago







Why does my code in setTimeout not work in JavaScript?

Aucun commentaire:

Enregistrer un commentaire