I have a javascript function.
How to check:
if function was called ( in <head></head>
section have this function), then not to call the function
if function was not called ( in <head></head>
section haven't this function), then call the function
like require_once
or include_once
with PHP
Invoking a JavaScript Function The code inside a function is not executed when the function is defined. The code inside a function is executed when the function is invoked. It is common to use the term "call a function" instead of "invoke a function".
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
Static variables
Here's how to create static (like in C) variables using self calling functions to store your static variables in a closure.
var myFun = (function() {
var called = false;
return function() {
if (!called) {
console.log("I've been called");
called = true;
}
}
})()
Abstract the idea
Here's a function that returns a function that only gets called once, this way we don't have to worry about adding boiler plate code to every function.
function makeSingleCallFun(fun) {
var called = false;
return function() {
if (!called) {
called = true;
return fun.apply(this, arguments);
}
}
}
var myFun = makeSingleCallFun(function() {
console.log("I've been called");
});
myFun(); // logs I've been called
myFun(); // Does nothing
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