How to make for loop happen every set amount of time?

Viewed 48

I need to add "momentum" to an object on a grid. The player can control the object as long as he hold the key down, however, I want the ability to press the key one time and the object will keep going in the direction of the key until he hits the border. I have create a simple for loop that works, however because it happens so fast the object just kind of "teleports" to the border. I want the for loop to happen for example every second. Here is a short part of my code:

        case "ArrowRight":
            if (snakex + 1 == 26) {
                temp += 1;
            }
            else {
                for (let i = snakex;  i < 26; i++) {
                    snakex += 1;
                    snake.style.gridArea = snakey + "/" + snakex; 
                }
            }
            break;

The game board is a 25x25 grid, if the fact that going to the right will result in going out of the board, the function will not do anything (temp is there for filling out a "fail mechanic" that I didn't add).

Without the for loop, the player needs to hold down the right key. This for loop makes it so the player needs to press it once, however it happens so fast it "teleports" like I said. Is it possible to make this loop happen every second, for example?

Any help would be appreciated. Thanks in advance!

1 Answers

you can control the speed of a loop by wrapping it in an async function, then you can write a custom function for sleep and await the sleep function at the beginning of every loop.

async function test() {
  for(let i =0; i < 10; i++ {
    await sleep(1000)
    //logic goes here
  }

}

function sleep(ms: number) {
  return new Promise(r => setTimeout(r,ms))
}
Related