For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/function/once.md.

once es-toolkit

Creates a new function that limits a function to be executed only once.

const onceFunc = once(func);

Usage

once(func)

Use once when you want to limit a function to be executed only once. Subsequent calls will return the result from the first call.

This is useful for logic that should only be executed once, such as initialization functions or event handlers. It prevents duplicate execution and ensures consistent results.

import { once } from 'es-toolkit/function';

// Example of an initialization function
const initialize = once(() => {
  console.log('Initializing app');
  return { status: 'initialized' };
});

console.log(initialize()); // Logs 'Initializing app', returns { status: 'initialized' }
console.log(initialize()); // Returns { status: 'initialized' } without logging
console.log(initialize()); // Returns { status: 'initialized' } without logging

// Example of an API call
const fetchConfig = once(async () => {
  console.log('Fetching configuration');
  const response = await fetch('/api/config');
  return response.json();
});

// Only the first call makes the actual API request
const config1 = await fetchConfig();
const config2 = await fetchConfig(); // Returns cached result

You can also use it with functions that take arguments.

import { once } from 'es-toolkit/function';

const logOnce = once((message: string) => {
  console.log(`Important message: ${message}`);
});

logOnce('Hello'); // Logs 'Important message: Hello'
logOnce('Hello again'); // Not logged (already called)
logOnce('Hello once more'); // Not logged (already called)

Parameters

funcFrequired

The function to restrict to a single execution.

Returns

Returns a new function that caches the result after the first call and returns the same result for subsequent calls.

F
Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.