Execute Function Only Once
Execute Function Only Once is a reusable JavaScript snippet. Wraps a function so it can only be called once. Subsequent calls return the result of the first invocation. The full implementation: function once(fn) { let called = false let result return function(...args) { if (!called) { called = true result = fn.apply(this, args) } return result } } // Usage const initialize = once(() => { console.log('Initialized!') return { ready: true } }) initialize() // "Initialized!" -> { ready: true } initialize() // -> { ready: true } (no console) This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.