Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!