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
}