Game walk by path in array
You just need clearTimeout
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout
let coord = { x: 0, y: 0 };
let myTimeout;
let goByPath = (path = [], coord = {}) => {
let i = 0;
clearTimeout(myTimeout); // stop previous calls
pathIteration(i, path, coord);
}
let pathIteration = (i, path, coord) => {
rect(coord);
if (i++ < path.length) {
myTimeout = setTimeout(() => { // store reference to timeout
coord = path[i - 1];
pathIteration(i, path, coord);
}, 500);
}
return i;
};
/* canvas grid for display purposes */
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var n = 10;
var size = Math.min(innerWidth, innerHeight);
var u = size / n;
var draw = function() {
size = Math.min(innerWidth, innerHeight);
u = size / n;
canvas.width = size;
canvas.height = size;
for (var y = 0; y < n; y++) {
for (var x = 0; x < n; x++) {
ctx.strokeStyle = '#000';
ctx.strokeRect(x * u, y * u, u, u);
}
}
};
draw();
var rect = (coord) => {
ctx.fillStyle = '#888';
ctx.fillRect(coord.x * u, coord.y * u, u, u);
};
/* example */
var path1 = [{x:0,y:1},{x:1,y:1},{x:1,y:2},{x:2,y:2}];
goByPath(path1, coord);
var path2 = [{x:1,y:3},{x:1,y:4},{x:1,y:5}];
setTimeout(() => { goByPath(path2, coord); }, 1600);
body {
margin: 0;
display: grid;
place-content: center;
}
<canvas></canvas>