Search code examples
javascriptjqueryprompt

how to console.log before prompt


How to avoid this stupid behaviour - prompt dialog brakes the code I need to decide what to enter into the dialog.

In this case that's the console.log. How to get prompt dialog after console is written.

$('.selx').on('change', function(){
  let a = $(this).val();
  console.log(a);
  let b = prompt('NEW TITLE');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='selx'>
<option value='323'>lorem</option>
<option value='525'>ipsum</option>
</select>


Solution

  • The console is asynchronous (there is always a small delay, usually you won't notice it). Calling prompt will halt everything else going on on the tab, including the console. Therefore you have to add a small delay to enable the browser updating the console before prompting:

     $('.selx').on('change', function(){
       let a = $(this).val();
       console.log(a);
       setTimeout(() => {
          let b = prompt('NEW TITLE');
       }, 10);
     });