Suppose I have a function named caller, which will call a function named callee:
void caller() { callee(); }
Now caller might be called many times in the application, and you want to make sure callee is only called once. (kind of lazy initialization), you could implement it use a flag:
void caller() { static bool bFirst = true; if(bFirst) { callee(); bFirst = false; } }
My opinion for this is it needs more code, and it needs one more check in every call of function caller.
A better solution to me is as follow: (suppose callee returns int)
void caller() { static int ret = callee(); }
But this can't handle the case if callee returns void, my solution is using the comma expression:
void caller() { static int ret = (callee(), 1); }
But the problem with this is that comma expression is not popular used and people may get confused when see this line of code, thus cause problems for maintainance.
Do you have any good idea to make sure a function is only called once?
var something = (function() { var executed = false; return function(value) { // if an argument is not present then if(arguments. length == 0) { if (! executed) { executed = true; //Do stuff here only once unless reset console.
It's fine to have a function even if only used once. Blocks of code should ideally only do one thing, perform one computation, one calculation. This makes it easy to work on the flow of your logic, instead of getting bogged down with huge blocks of code.
In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.
You could use this:
void caller() { static class Once { public: Once(){callee();}} Once_; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With