I am trying to code chess as I play it a lot and I am trying to use setTimeout() for my move function for the pawns. I try to set it to 10 ms delay and then call it self so I am using this code:
function pawnMoveFunc(piece) {
console.log(colourToMove, mouse.x, mouse.y);
let actualPawnX = piece.x - piece.offset;
if (piece.colour == colourToMove) {
if (mouse.x != actualPawnX || mouse.y != piece.y) {
piece.x = mouse.x + piece.offset;
piece.y = mouse.y;
drawAfterMove();
}
else {
if (mouse.x == actualPawnX && mouse.y == piece.y && stopLoop == false) {
pawnMoveFunc(piece)
}
}
}
else {
console.log('wrong colour');
}
}
I am calling this function from my move function in my pawn class:
class Pawn{
constructor(colour, x, y) {
if (colour == 'white') {
this.img = document.getElementById('whitePawn')
}
else{
if (colour == 'black') {
this.img = document.getElementById('blackPawn')
}
}
this.colour = colour;
this.offset = 7.5;
this.x = x * tileSize + this.offset;
this.y = y * tileSize;
this.width = 35;
this.height = 50;
}
draw() {
ctx.drawImage(this.img, this.x, this.y, this.width, this.height)
}
move() {
if (this.x - this.offset == mouse.x && this.y == mouse.y) {
setTimeout(10, pawnMoveFunc(this));
}
stopLoop = true;
stopLoop = false;
}
}
I am calling this move function from a function that repeats calling each pawns move function all the time.
When I run this code and try to move a pawn I get a recursion error at the pawn move function but I don't know why.
Also any tips for my code would be appreciated!
There are two problems in your code.
The first problem is that setTimeout takes two parameters (in order): function, and then delay. You are providing the delay parameter before the function parameter.
The second problem is that the function parameter should be a function. What you are doing is you are already calling the function instead of providing setTimeout with a function to call.
This is the updated line of code (line 28 from the top of your Pawn class):
setTimeout(() => pawnMoveFunc(this), 10);
Note: () => creates an arrow function.