[Home] > Snippets  > Languages  > JavaScript  > Fn  >  Execute a function once

Execute a function once

JavaScript

const once = (fn) => (
(ran = false) =>
() =>
ran ? fn : ((ran = !ran), (fn = fn()))
)()

Examples

let n = 0
const incOnce = once(() => ++n)
incOnce() // n = 1
incOnce() // n = 1
incOnce() // n = 1