Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
i tried creating a javascript function that only runs once but its always running the else statement

i'm making a basic javascript function that works with onclick but it's always running the else statement which I only want it to run once

here's my script

function onlyOnce() {
    var runOnce = false;
    console.log("i'm running but i didn't go to the else statement yet")
    if (runOnce) {
        return
    } else {
        console.log("i'm running and i'm in the else statement")
        return runOnce = true;   
    }
}

any help will be appreciated

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The runOnce variable is defined in the function, and after you leave the function its value is forgotten. When entering the function, its value will be set to false again.

One way to solve this, is by bringing the variable outside the function:

let runOnce = false; // let is usually recommended over var

function onlyOnce() {
    console.log("i'm running but i didn't go to the else statement yet");
    if (runOnce) {  
        return;
    } else {
        console.log("i'm running and i'm in the else statement");
        runOnce = true;
    }
}

You could also make a class such that the function/method is associated with the data:

class Something {
    constructor() {
        this.runOnce = false;
    }

    onlyOnce() {
        console.log("i'm running but i didn't go to the else statement yet");
        if (this.runOnce) {
            return;
        } else {
            console.log("i'm running and i'm in the else statement");
            this.runOnce = true;
        }
    }
}

let something = new Something();

something.onlyOnce(); // Prints second statement
something.onlyOnce(); // Prints first statement
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda