Skip to content

once() function

创建一个只在第一次调用时执行 f 的函数。后续调用不会再次执行 f,而是返回第一次执行的结果。

返回的函数保留 fthis 和参数类型。

Signature:

typescript
function once<F extends (...args: any[]) => any>(f: F): F;

Example

ts
let count = 0;
const init = once((a: number) => {
  count += 1;
  return a * 10;
});

init(1); // 10 - 调用了 `f`
init(2); // 10 - 不再调用 `f`,返回第一次的结果
count; // 1

Open Source Code

Released under the Apache-2.0 License.