I need to create a function which can be executed only once, in each time after the first it won't be executed. I know from C++ and Java about static variables that can do the work but I would like to know if there is a more elegant way to do this?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
If your using Node.js or writing JavaScript with browserify, consider the "once" npm module:
You could simply have the function "remove itself"
But this may not be the best answer if you don't want to be swallowing errors.
You could also do this:
I need it to work like smart pointer, if there no elements from type A it can be executed, if there is one or more A elements the function can't be executed.
If you're using Ramda, you can use the function "once".
A quote from the documentation:
If you want to be able to reuse the function in the future then this works well based on ed Hopp's code above (I realize that the original question didn't call for this extra feature!):
The output look like:
Reusable
invalidate
function which works withsetInterval
:Try it on JSBin: https://jsbin.com/vicipar/edit?js,console
Variation of answer from Bunyk
Replace it with a reusable NOOP (no operation) function.