Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

javascript - How to restart a function from inside it

I'm trying to restart the function non() with the if statement inside. I have looked at other sources and none of them seem to work. here is my code. It's in French btw.

var click = 9;

function non() {
  var i;
  var message = document.getElementById("message");

  //Affiche un message chaque fois que le bouton non //estcliquer
  for (i = 0; i < 1; i++) {
    message.innerHTML += "Es-tu près !!OUI!! ou !!NON!!<br>";
  }

  if (!(click--)) {
    alert("Es-tu près");
    non();
  }

  document.getElementById("boutonNon").click;
}
<div id="divNon">
  <button class="bouton boutonOui" id="boutonNon"
      onclick="non()" value="reset">Non</button>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could remove the loop and use a recursive function that calls out to a promise and waits till it resolves before it fires again.

The HTML children will not be added until all the alerts have been accepted.

var message = document.getElementById("message");
var clicksRemaining = 9;

const handleClick = () => new Promise(res => {
  message.append(document
    .createTextNode(`${clicksRemaining}) Es-tu près !!OUI!! ou !!NON!!`));
  message.append(document.createElement('br'));
  alert("Es-tu près");
  res();
});

function non() {
  handleClick().then(() => {
    if (clicksRemaining --> 1) {
      non();
    }
  });
}

document.getElementById('boutonNon').click();
<div id="divNon">
  <button class="bouton boutonOui" id="boutonNon"
      onclick="non()" value="reset">Non</button>
</div>
<div id="message"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...