javascript - Is there a way to check for if certain conditions are true on the second call of a function? -
So I want to call a function
myfunction (); I want to be able to call my code once, but okay but if my code says for the second time, then I want to see if some conditions are correct and if they I do not want to run the function, I do not want to run the function. If these terms are not correct, then I want to run the function as always. I just want to know that some specific only for the second call of the function is true and do not allow my function to run again, as long as these conditions are no longer true.
If (condition) {// do not run the function code until this is not true. } And {// business normally, run the code} I always want to do this on the second call in the function. So first call the function, no checking. On the second call, check. On the third call check on the third call check etc. In fact, check every other call on the function, to see if some conditions are true and if they are, do not run the function code. I highly appreciate your feedback.
It is quite easy. Since what you are looking for is basically a function that modifies your behavior according to some internal condition, this is an ideal application for the object:
var o = { Call: 0, fn: function) {If (++ this.calls% 2) {console.log ('weird call'); } And {console.log ('even call'); }}} If you have only one function (no object), then you can use one to return the function:
< Code> var fn = (function () {var call = 0; return function () (if (++ call% 2) {console.log ('strange call');} and {console.log ('so far That call ');}}}) (); Its code has the advantage of the encoder of the variable call: without access or tampering it outside the function .
A cautionary note as it is received Is called "side effect": without understanding the behavior of the function, the behavior of the function can not be predicted. I am not being fanatic and say that the side effects are always bad, but you have to be careful with them : Make sure they understand, and that your document is clear about what is happening.
Comments
Post a Comment