Skip to content
Advertisement

Synchronous javascript: How to continue script after input value is set?

I have this javascript:

function getImage(input)
{ 
status++;
var base64 = $('#edit').croppie('result', {
    type: 'base64',
    size: 'viewport',
    format: 'jpeg',
    }).then(function(base64){

  $('#input').val(base64); // THIS SHOULD BE SYNCHRONOUS
  status--; // THIS SHOULD ONLY RUN AFTER THE #INPUT HAS ALREADY AN ASSIGNED VALUE ON THE PREVIOUS LINE

});

}

I need to execute the line with status--; only after $('#input').val(base64); on the previous line is securely finished.

Is there some simple solution?

Advertisement

Answer

What makes you think, it doesn’t? The UI might not be updated yet because JS runs on the browsers UI thread and thus, the UI thread is blocked while the JS is still running, but the input does have the correct value internally.

document.getElementById("thebutton").addEventListener("click", () => {
  var before = $("#theinput").val();
  $("#theinput").val(13);
  var after = $("#theinput").val();
  alert("ok");
  console.log(`before: '${before}'   after: '${after}'`)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="theinput">
<button id="thebutton">click me</button>

So if you really want to continue only after the UI is updated, you need to make for instance a timeout (can even be zero) to return to the browsers UI thread, which will update the UI and then take the next js from the eventloop.

document.getElementById("thebutton").addEventListener("click", () => {
  var before = $("#theinput").val();
  $("#theinput").val(13);
  var after = $("#theinput").val();
  console.log(`before: '${before}'   after: '${after}'`)

  setTimeout(() => { alert("ok");}, 0);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="theinput">
<button id="thebutton">click me</button>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement