DIY-DS
DIY-DS

Reputation: 263

HTML button text won't change before infinite loop

In the code below:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<button type="button" class="btn btn-danger" id="TxChg">Proceed</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script>
  idcate = 0;

  function checkbuff() {
    while ((idcate == 0)) {
      mis = new Date().getSeconds() % 30;
      if (mis == 2) {
        idcate = 1;
      }
    }
  }
  $('#TxChg').click(function() {
    document.getElementById("TxChg").innerHTML = "<i class='fa fa-refresh fa-spin'></i>Processing...";
    checkbuff();
  });
</script>

I want to let the "Txchg" button change its text to "Processing..." before the checkbuff() fucntion run.

I don't know why this code always run the checkbuff() function first then I will see the button changed its text?

Upvotes: 0

Views: 41

Answers (1)

Taplar
Taplar

Reputation: 24965

Rather than spam looping your system, since you are waiting for a particular second to occur, you should perform your logical loop on the second. And you can setTimeout your initial call as well to give the browser a chance to redraw.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<button type="button" class="btn btn-danger" id="TxChg">Proceed</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script>
  idcate = 0;

  function checkbuff() {
    if (!idcate) {
      var mis = new Date().getSeconds() % 30;
      
      console.log(mis);
      
      if (mis === 2) {
        idcate = 1;
      } else {
        setTimeout(checkbuff, 1000);
      }
    }
  }
  
  $('#TxChg').click(function() {
    document.getElementById("TxChg").innerHTML = "<i class='fa fa-refresh fa-spin'></i>Processing...";
    setTimeout(checkbuff, 0);
  });
</script>

Upvotes: 1

Related Questions