I am writing an algorithm for iterating over the elements of an array at a given speed. I use this to iterate through the cells on the game map in an array of paths that I find.
I need that when a new function is called with a new array, the last function call stops working.
This will be used to move along the path, at the click of a mouse. Now, if we call the first function, it will go along the path, but if, before the end of the path, the function is called again with a new path, then both of them will continue to change the current coordinate.
The object must interrupt its path at the place it had come to when it first called the function and continue its path in the second function call.
Here is a sample code of how it works now:
let coord = {x:0,y:0}
let goByPath = (path=[],coord={})=>{
let i = 0;
pathIteration(i,path,coord)
}
let pathIteration = (i,path,coord)=>{
if(i++<path.length){
setTimeout(()=>{
coord = path[i-1];
console.log(coord);
pathIteration(i,path,coord);
},500);
}
return i;
};
path1 = [{x:0,y:1},{x:1,y:1},{x:1,y:2},{x:2,y:2}];
path2 = [{x:1,y:3},{x:1,y:4},{x:1,y:5}];
goByPath(path1, coord);
setTimeout(()=>{
goByPath(path2, coord);
},900);
Output to console now:
{
"x": 0,
"y": 1
}
{
"x": 1,
"y": 1
}
{
"x": 1,
"y": 3
}
{
"x": 1,
"y": 2
}
{
"x": 1,
"y": 4
}
{
"x": 2,
"y": 2
}
{
"x": 1,
"y": 5
}
Needed output:
{
"x": 0,
"y": 1
}
{
"x": 1,
"y": 1
}
{
"x": 1,
"y": 3
}
{
"x": 1,
"y": 4
}
{
"x": 1,
"y": 5
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With