onetime

中文文档
8.0.0发布于 2026/02/02MITTypeScriptES Module近 30 天下载 7.8亿

Ensure a function is only called once

原始使用文档
文档目录5 节
  1. Install
  2. Usage
  3. API
  4. onetime(fn, options?)
  5. onetime.callCount(fn)

onetime

Ensure a function is only called once

When called multiple times it will return the return value from the first call.

Unlike the module once, this one isn't naughty and extending Function.prototype.

Install

npm install onetime

Usage

import onetime from 'onetime';

let index = 0;

const foo = onetime(() => ++index);

foo(); //=> 1
foo(); //=> 1
foo(); //=> 1

onetime.callCount(foo); //=> 3
import onetime from 'onetime';

const foo = onetime(() => {}, {throw: true});

foo();

foo();
//=> Error: Function `foo` can only be called once

API

onetime(fn, options?)

Returns a function that only calls fn once.

fn

Type: Function

The function that should only be called once.

options

Type: object

throw

Type: boolean
Default: false

Throw an error when called more than once.

onetime.callCount(fn)

Returns a number representing how many times fn has been called.

Note: It throws an error if you pass in a function that is not wrapped by onetime.

import onetime from 'onetime';

const foo = onetime(() => {});

foo();
foo();
foo();

console.log(onetime.callCount(foo));
//=> 3

fn

Type: Function

The function to get call count from.

版本与发布记录

onetime 共发布 15 个版本,首次发布于 2013/12/14;过去 12 个月发布了 1 个版本。

版本发布日期距今
8.0.0latest2026/02/029 个月前
7.0.02023/11/062 年前
6.0.02021/04/085 年前
5.1.22020/08/106 年前
5.1.12020/08/026 年前
5.1.02019/04/027 年前

关于 onetime 的常见问题

onetime 是什么?

Ensure a function is only called once

如何安装 onetime?

在项目目录运行 npm install onetime,或使用 pnpm add / yarn add / bun add。

onetime 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

onetime 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

onetime 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

onetime 可以商用吗?

onetime 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

onetime 的下载量有多少?

根据 npm 官方下载统计,onetime 在 2026/10/05 – 2026/11/03 这 30 天内被下载 783,473,293 次,日均约 26,115,776 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

onetime 还在维护吗?

最新版本 8.0.0 发布于 2026/02/02(9 个月前);至今共发布 15 个版本,其中过去 12 个月发布了 1 个;首次发布于 2013/12/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。