<?php
// using_queue_microtask.php
// RJM Programming - December, 2024
// Thanks to https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide

  $thejcode="const callback = () => console.log(\"Regular timeout callback has run\");

const urgentCallback = () => console.log(\"*** Oh no! An urgent callback has run!\");

const doWork = () => {
  let result = 1;

  queueMicrotask(urgentCallback);

  for (let i = 2; i <= 18; i++) {
    result *= i;
  }
  return result;
};

console.log(\"Main program started\");
setTimeout(callback, 0);
console.log(`18! equals \${doWork()}`);
console.log(\"Main program exiting\");
";
  if (isset($_POST['jcode'])) {
    $thejcode=base64_decode($_POST['jcode']);
  }
?>
<html>
<head>
<title>Using queueMicrotask - RJM Programming - December, 2024 - thanks to https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide</title>
<style>
  th { background-color: yellow; }
  td { vertical-align: top; }
  #tdleft { background-color: #f9f9f9; width:60%; }
  #tdright { background-color: #e0e0e0; }
  textarea { width: 100%; height: 200px; }
</style>
<script type=text/javascript>
  function consolelog(what) {
    //document.getElementById('tdright').innerHTML+=what.replace(String.fromCharCode(10), '<br>').replace(String.fromCharCode(10), '<br>').replace(String.fromCharCode(10), '<br>');
    document.getElementById('tdright').value+=String.fromCharCode(10) + what;
    console.log(what);
  }
  
  function doit(tdiho) {
    document.getElementById('jcode').value=window.btoa(tdiho.innerText);
    document.getElementById('mysub').click();
  }
  
  function wbtoait() {
    return true;
  }
</script>
</head>
<body>
<h1>Using queueMicrotask</h1>
<h3>RJM Programming - December, 2024</h3>
<h4>Thanks to <a target=_blank title='https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide' href='//developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide'>https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide</a></h4>
<table cellpadding=8 cellspacing=8 style=width:98%; border=2>
<tr><th>Your editable Javascript ...</th><th>The console results ...</th></tr>
<tr><td id=tdleft contenteditable=true onblur=doit(this);><?php echo str_replace("\n","<br>",$thejcode); ?></td><td><textarea id=tdright></textarea></td></tr>
</table>
<form target=_self onsubmit='return wbtoait();' style=display:none; id=myform method=POST action=./using_queue_microtask.php>
<textarea style=display:none; name=jcode id=jcode value=''></textarea>
<input type=submit style=display:none; id=mysub value=Submit></input>
</form>
<script type=text/javascript>
<?php echo str_replace('console.log(','consolelog(',$thejcode); ?>
</script>
</body>
</html>