how to avoid recursion or to fix the problem?

Teaching JS trying to do a ticatactoe game and got a problem with recursion, specifically with ‘Maximum call stack size exceeded’.

When I try to make a random move by the computer player I make a random number, which then will be checked of his value in array called gameState.
So, if this value has defined already (there are X or O mark in a cell), I need to generate a random number again. So I need to stop this infinite loop when all cells are marked or I’ll get an error ‘Maximum call stack size exceeded’.

Can you please take a look, am I do the right thing or it is generally wrong?
Actually, I thought about another implementation of this game scene, but I thought if i’ve started with that I should lead this to the end


let gameState = ["", "", "", "", "", "", "", "", "",];
let playerAi = "O";

// ai's turn
function playerAiTurn() {
    let randomNum = Math.floor(Math.random() * gameState.length);
    if (gameState[randomNum] === '') {
    gameState[randomNum] = playerAi;
    document.getElementById(randomNum).innerHTML = playerAi;
    resultCheck();
    } else {
        playerAiTurn()
    };
};