Javascript Running Code Once
I only want my JavaScript to run once, but I cannot control how many times the javascript file is executed. Basically I'm writing a tiny JS snippet into a CMS, and the CMS is actua
Solution 1:
Try this:
var doneTheStuff;
function whatever() {
if (!doneTheStuff) {
doneTheStuff = true;
// do the stuff
}
}
Redundant variable declarations don't affect the value of the variable. Once one of the functions has set the variable to true
, the others won't do anything.
Solution 2:
if (typeof code_happened === 'undefined') {
window.code_happened = true;
// Your code here.
}
The typeof
check gets you around the fact that the global hasn't been declared. You could also just do if (!window.code_happened)
since property access isn't banned for undefined properties.
Solution 3:
Use a closure, and set a flag. If the flag is true
, just return:
if ( ! window.never_called_again ) {
window.never_called_again = (function () {
var ran = false;
returnfunction (args) {
if ( ran ) return;
ran = true;
// Do stuff
};
}());
}
Here's the fiddle: http://jsfiddle.net/U2NCs/
Solution 4:
With jQuery, the function .one() may be useful : http://api.jquery.com/one/
W3School exemple here : http://www.w3schools.com/jquery/event_one.asp
Post a Comment for "Javascript Running Code Once"