Making sure a javascript function is not called, if called already
I am using google maps for a project. I need to be able to hide and display multiple maps. I cannot use a basic toggleDiv type function alone. This is because Google maps will ignore the intended size of the div when the div is set to display: none from CSS. (for whatever reason it is fine with being toggled by javascript.) I could use GSize(width, height) but it cannot handle percentages. Since I need the map to be 100%, 100%, this is not an option. I figured out a way around it which is to call the second map's function using onClick, rather then loading all the functions us开发者_如何学编程ing body onLoad. But, then the zoom of the map is not saved and the map is just reloaded.
So, I need to check if a function has been called, and if so, do not recall it. I cannot figure out how to do this. Any help is appreciated.
Thank you.
Another "lazy" variant:
var doOnce = function () {
// do something
doOnce = function () {}
}
As for the original problem, if the function you want to run once is the click event handler, you'd better remove the click event listener.
Define a variable as such. var beenFired = false;
in the function do this:
function myFunction()
{
if(!beenFired)
{
//TODO FUNCTION
beenFired = true;
}
}
That will check to see if hasn't been fired yet and if not fire it. You could even do it around the function call itself.
if(!beenFired)
myFunction()
function myFunction()
{
//TODO FUNCTION
beenFired = true;
}
var func = (function(){
var first = true;
return function( a, b, c){
if ( !first ){
return;
}
first = false;
console.log( arguments );
}
})();
func( 1, 2, 3); // in console : [ 1, 2, 3]
func( 1, 1, 1); // nothing happens;
If I understand:
var isCalled = false;
function f() {
if (!isCalled) {
isCalled = true;
// ...
}
}
精彩评论