Javascript running code once

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

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 actually calling it 5-10 times. So solutions like this:

function never_called_again(args) {   // do some stuff   never_called_again = function (new_args) {    // do nothing   } } never_called_again(); 

Don't seem to work because as soon as my snippet is run again from the top the function is re-declared, and 'do some stuff' is re-evaluated. Perhaps I'm just not doing it properly, I'm not great with JS. I'm considering using something like try-catch on a global variable, something like

if (code_happened == undefined) {     \\ run code      code_happened = true; } 

EDIT: There is a consistent state e.g. if I set a variable I can see when my snippet is run again. But having to declare it before I access it, I don't know how to say 'does this variable exist yet'

回答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.



回答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.



回答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;         return function (args) {             if ( ran ) return;             ran = true;             // Do stuff         };     }()); } 

Here's the fiddle: http://jsfiddle.net/U2NCs/



回答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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!