Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...