Javascript运行一次代码 [英] Javascript running code once

查看:70
本文介绍了Javascript运行一次代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只希望我的JavaScript运行一次,我无法控制javascript文件的执行次数。基本上我正在将一个小的JS片段写入CMS,而CMS实际上称它为5-10次。所以像这样的解决方案:

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();

似乎没有用,因为只要我的代码片段从顶部再次运行,该功能就是重新宣布,并重新评估做一些事情。也许我只是没有正确地做到这一点,我对JS不太好。我正在考虑在全局变量上使用类似try-catch的东西,比如

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;
}

编辑:有一致的状态,例如:如果我设置了一个变量,我可以看到我的代码片段再次运行时。但是在我访问它之前必须声明它,我不知道怎么说'这个变量是否存在'

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'

推荐答案

试试这个:

var doneTheStuff;
function whatever() {
  if (!doneTheStuff) {
    doneTheStuff = true;
    // do the stuff
  }
}

冗余变量声明不会影响变量的值。一旦其中一个函数将变量设置为 true ,其他函数将不会执行任何操作。

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.

这篇关于Javascript运行一次代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆