useState update in A Timeout
Use ref to save the newest value of variable
function App () {
const ref = useRef()
ref.current = {distance, nextWayPointId, nextWayPoint}
useEffect(()=>{
},[nextWayPointId])
useEffect(()=>{
let enemyTimeID = setTimeout(()=>{
const currentPosition = [location.left, location.top]
setDistance(getDistance(currentPosition,ref.current.nextWayPoint))
if (ref.current.distance < 1) {
setNextWayPointID(prev=>prev+1)
setNextWayPoint(waypath.stage1[ref.current.nextWayPointId])
console.log(ref.current.nextWayPointId)
console.log(ref.current.nextWayPoint)
}else {
const lengthX = nextWayPoint[0] - currentPosition[0]
const lengthY = nextWayPoint[1] - currentPosition[1]
const step = Math.round(ref.current.distance/speed)
console.log(ref.current.distance)
const top = location.top + (lengthY / step)
const left = location.left+ (lengthX / step)
setLocation({top,left})
}
},100)
return ()=>{
clearTimeout(enemyTimeID);
}
},[location,nextWayPoint])
}
Last updated