Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda