如何使函数的一部分只执行一次,直到允许其他方式执行

cab*_*nto 2 javascript function

我怎样才能repeatedFunction()反复调用一个javascript函数(),但是这样做,让我们说一个alert("This function is being executed for the first time"),只在第一次激活repeatedFunction(),但是//other code它总是被激活?而且,我怎样才能让alert()允许再次被激活,就好像repeatedFunction()第一次被执行一样?

Pra*_*man 6

你可以设置一个标志.比如说,您有以下代码:

var flagAlertExecd = false;
function repeatThis () {
  if (!flagAlertExecd) {
    alert("Only once...");
    flagAlertExecd = true;
  }
  // Repeating code.
}
Run Code Online (Sandbox Code Playgroud)

要重复此代码,最好使用setInterval.

setInterval(repeatThis, 1000);
Run Code Online (Sandbox Code Playgroud)