Skip to main content

Command Palette

Search for a command to run...

JavaScript - One-time function

Published
1 min read
JavaScript - One-time function
D

I'm a Software Engineer with 9+ years of experience. I've extensive knowledge of different technologies and programming languages. I've skills in Web Development, Databases, and Agile Methodologies. I'm constantly looking to explore new technologies and new opportunities to learn.

Sometimes we need something to be executed only once in our code, in JavaScript we can create a one-time function to do something only once. Take a look at the code below 👇

const oneTimeFunction = function () {
  let executed = false
  return function() {
   if (!executed) {
      executed  = true
      // Do something here one time
      console.log('Loading settings...')
   }
  }
}()

oneTimeFunction() // Output -> Loading settings..
oneTimeFunction() // Nothing happens

Quick Demo

Screen Recording 2022-10-14 at 01.36.11.gif