Есть платформа, каторую надо сдвинуть при нажатии на стрелочки. Пробела в том, что когда я быстро меняю направление, появляется задержка.
const platform = document.getElementById("platform");
let isPlatformMoving = false;
let platformMovingDirection;
document.addEventListener("keydown", ()=>{
const keyCode = event.keyCode;
if (keyCode === 37) {
console.log(platformMovingDirection);
if(platformMovingDirection === "left"){
return;
} else if(platformMovingDirection === "right") {
clearInterval(isPlatformMoving);
}
platformMovingDirection = "left";
isPlatformMoving = setInterval(movePlatform, 0);
return;
} else if (keyCode === 39) {
console.log(platformMovingDirection);
if(platformMovingDirection === "right"){
return;
} else if(platformMovingDirection === "left") {
clearInterval(isPlatformMoving);
}
platformMovingDirection = "right";
isPlatformMoving = setInterval(movePlatform, 0);
return;
}
});
document.addEventListener("keyup", ()=> {
if (isPlatformMoving) {
clearInterval(isPlatformMoving);
isPlatformMoving = false;
platformMovingDirection = undefined;
}
});
function movePlatform() {
const position = parseFloat(getComputedStyle(platform).getPropertyValue("left"));
if(platformMovingDirection === "left") {
platform.style.left = ( position - 1 ) + "px";
} else if(platformMovingDirection === "right") {
platform.style.left = ( position + 1 ) + "px";
}
}