Skip to content
the poor coder

run function once javascript

Poor Man
Published
Reading time
1 min read
On this page

How to Run a Function Once in JavaScript?#

If you want to execute a function only once in JavaScript, there are several ways to achieve this. Let's explore a few of them here.

1. Using a Flag Variable#

One way to run a function once in JavaScript is by using a flag variable. A flag variable is a boolean value that you set to 'true' once the function has been executed. Here's an example:

Text

let executed = false;

function runOnce() {
  if (!executed) {
    executed = true;
    // Your code here...
  }
}

In the above code, the 'executed' flag variable is initially set to 'false'. When the 'runOnce()' function is called, it checks if the 'executed' variable is 'false'. If it is, it sets the 'executed' variable to 'true' and executes the code inside the 'if' block.

2. Using the 'once' Method#

The 'once' method is a built-in method in JavaScript that allows you to run a function once. Here's an example:

Text

function runOnce() {
  // Your code here...
}

const runOnceWrapper = _.once(runOnce);
runOnceWrapper(); // This will run the 'runOnce' function only once

In the above code, we're using the 'once' method from the Lodash library to wrap our 'runOnce' function. The 'runOnceWrapper' variable is then called to execute the 'runOnce' function only once.

3. Using the Immediately-Invoked Function Expression (IIFE)#

The IIFE is a JavaScript function that is executed as soon as it is defined. Here's an example:

Text

(function runOnce() {
  // Your code here...
})();

In the above code, we're defining an anonymous function and immediately invoking it using the parentheses at the end. This will execute the function only once.

Conclusion#

These are some of the ways to run a function once in JavaScript. Depending on your use case, you can choose any of these methods to achieve your goal.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC