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
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