Skip to content
Advertisement

How to make a function in Node JS run only once

I am creating a simple tictactoe terminal game in JS. I use the variable named player1Input to get user prompt. If the prompt is not equal to “X”, I call the function again to make sure the user input the right input. If I enter the wrong input multiple times, the function (player1Game) ends up being called multiple times instead of once. How do I get it to just be called once. I put a snippet of my code at the bottom.I commented the part of the code that makes the function run twice

function player1Game () {
    let player1Input = prompt(`${player1Name.charAt(0).toUpperCase() + player1Name.slice(1) } please enter "x": `);
    //Create an error that responds if player 1 does not type x
    if (player1Input !== "x") {
        console.log("Please make sure you type in x")
        player1Game(); 
       //the function runs multiple times here instead of once.
       // How do I get it to run only once.
        
    }

Advertisement

Answer

You still aren’t showing the whole context here, but perhaps you just need to return after you call it again so that the rest of the function doesn’t execute when the function doesn’t meet the input requirements:

function player1Game () {
    let player1Input = prompt(`${player1Name.charAt(0).toUpperCase() + player1Name.slice(1) } please enter "x": `);
    //Create an error that responds if player 1 does not type x
    if (player1Input !== "x") {
        console.log("Please make sure you type in x")
        player1Game(); 
        // return so it doesn't execute any more of the function
        return;          
    }
    // code here will only get called if the `player1Input` 
    // meets the above critera

    // Rest of your code here...
}

Or, you could use an if/else:

function player1Game () {
    let player1Input = prompt(`${player1Name.charAt(0).toUpperCase() + player1Name.slice(1) } please enter "x": `);
    //Create an error that responds if player 1 does not type x
    if (player1Input !== "x") {
        console.log("Please make sure you type in x")
        player1Game(); 
    } else {
        // code here will only get called if the `player1Input` 
        // meets the above critera

        // Rest of your code here...
    }
}

FYI, there’s nothing special here. This is just normal function control flow in Javascript. If you want no more of the function to execution then insert a return statement. Or protect branches of code with an if/else so a condition will control what code executes.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement