Kaido Kert | f585e26 | 2020-06-08 11:42:28 -0700 | [diff] [blame] | 1 | # onetime [](https://travis-ci.org/sindresorhus/onetime) |
| 2 | |
| 3 | > Ensure a function is only called once |
| 4 | |
| 5 | When 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 |
| 20 | let i = 0; |
| 21 | |
| 22 | const foo = onetime(() => i++); |
| 23 | |
| 24 | foo(); //=> 0 |
| 25 | foo(); //=> 0 |
| 26 | foo(); //=> 0 |
| 27 | ``` |
| 28 | |
| 29 | ```js |
| 30 | const foo = onetime(() => {}, {throw: true}); |
| 31 | |
| 32 | foo(); |
| 33 | |
| 34 | foo(); |
| 35 | //=> Error: Function `foo` can only be called once |
| 36 | ``` |
| 37 | |
| 38 | |
| 39 | ## API |
| 40 | |
| 41 | ### onetime(fn, [options]) |
| 42 | |
| 43 | Returns a function that only calls `fn` once. |
| 44 | |
| 45 | #### fn |
| 46 | |
| 47 | Type: `Function` |
| 48 | |
| 49 | Function that should only be called once. |
| 50 | |
| 51 | #### options |
| 52 | |
| 53 | Type: `Object` |
| 54 | |
| 55 | ##### throw |
| 56 | |
| 57 | Type: `boolean`<br> |
| 58 | Default: `false` |
| 59 | |
| 60 | Throw an error when called more than once. |
| 61 | |
| 62 | |
| 63 | ## License |
| 64 | |
| 65 | MIT © [Sindre Sorhus](https://sindresorhus.com) |