blob: 95eb3b7c9e1c4474a9f108878f5999645e3b6aba [file] [log] [blame] [view]
Kaido Kertf585e262020-06-08 11:42:28 -07001# onetime [![Build Status](https://travis-ci.org/sindresorhus/onetime.svg?branch=master)](https://travis-ci.org/sindresorhus/onetime)
2
3> Ensure a function is only called once
4
5When called multiple times it will return the return value from the first call.
6
7*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty extending `Function.prototype`.*
8
9
10## Install
11
12```
13$ npm install --save onetime
14```
15
16
17## Usage
18
19```js
20let i = 0;
21
22const foo = onetime(() => i++);
23
24foo(); //=> 0
25foo(); //=> 0
26foo(); //=> 0
27```
28
29```js
30const foo = onetime(() => {}, {throw: true});
31
32foo();
33
34foo();
35//=> Error: Function `foo` can only be called once
36```
37
38
39## API
40
41### onetime(fn, [options])
42
43Returns a function that only calls `fn` once.
44
45#### fn
46
47Type: `Function`
48
49Function that should only be called once.
50
51#### options
52
53Type: `Object`
54
55##### throw
56
57Type: `boolean`<br>
58Default: `false`
59
60Throw an error when called more than once.
61
62
63## License
64
65MIT © [Sindre Sorhus](https://sindresorhus.com)