Add once snippet
This commit is contained in:
27
snippets/once.md
Normal file
27
snippets/once.md
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
### once
|
||||||
|
|
||||||
|
Ensures a function is called only once.
|
||||||
|
|
||||||
|
Utilizing a closure, use a variable flag and set it to true once the function is called
|
||||||
|
for the first time, preventing it from being called again. Allow the function to be supplied
|
||||||
|
with an arbitrary number of arguments using the spread/rest (`...`) operator.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const once = fn => {
|
||||||
|
let called = false;
|
||||||
|
return (...args) => {
|
||||||
|
if (!called) {
|
||||||
|
fn(...args);
|
||||||
|
called = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
const startApp = event => {
|
||||||
|
// initializes the app
|
||||||
|
console.log(event); // access to any arguments supplied
|
||||||
|
};
|
||||||
|
document.addEventListener('click', once(startApp)); // only runs `startApp` once upon click
|
||||||
|
```
|
||||||
@ -95,6 +95,7 @@ negate:logic
|
|||||||
nthElement:array
|
nthElement:array
|
||||||
objectFromPairs:object
|
objectFromPairs:object
|
||||||
objectToPairs:object
|
objectToPairs:object
|
||||||
|
once:function
|
||||||
onUserInputChange:browser
|
onUserInputChange:browser
|
||||||
orderBy:object
|
orderBy:object
|
||||||
palindrome:string
|
palindrome:string
|
||||||
|
|||||||
Reference in New Issue
Block a user