CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

once

Creates a function that invokes the given function only once and returns the result from the first invocation for all subsequent calls.

once(fn):(...args: TArgs) => TResult

Parameters

fn(...args: TArgs) => TResultrequired

The function to invoke only once.

Returns

(...args: TArgs) => TResult

Returns a function that executes the original function only on its first call and returns the stored result afterward.

Examples

01

Basic usage

The original function is executed only on the first call.

TypeScript
const initialize = once(() => {
  console.log("Initialized");
  return "ready";
});

console.log(initialize());
// Initialized
// ready

console.log(initialize());
// ready

console.log(initialize());
// ready
02

First result is reused

After the first invocation, the stored result is returned even when later calls use different arguments.

TypeScript
const getValue = once((value: number) => value * 2);

console.log(getValue(5));
// 10

console.log(getValue(10));
// 10

console.log(getValue(20));
// 10
03

Passing multiple arguments

All arguments from the first call are passed to the original function.

TypeScript
const createMessage = once(
  (name: string, age: number) => {
    return `${name} is ${age} years old`;
  },
);

console.log(createMessage("Amir", 20));
// Amir is 20 years old

console.log(createMessage("Ali", 25));
// Amir is 20 years old
04

Useful for initialization

once can be used when an operation should happen only during the first invocation.

TypeScript
const setup = once(() => {
  console.log("Setup completed");
  return true;
});

setup();
// Setup completed

setup();
// No output
05

Original function is not called again

Once the function has been called, subsequent calls return the stored result without invoking the original function.

TypeScript
let count = 0;

const increment = once(() => {
  count += 1;
  return count;
});

console.log(increment());
// 1

console.log(increment());
// 1

console.log(count);
// 1
Built with@cyref/js·Official documentation