Search code examples
javascriptasynchronousinputasync-awaitalert

why can't I clear the email field before window.alert()?


I want to clear an input type="email" before the alert() appears on the screen (by clicking the button). I just got this to happen using a promise that resolves in 20ms. But why if I remove line 11 (the promise line) it stops working? the commands being executed are not synchronous and therefore they should be executed in order? (correct me if I'm talking nonsense, I'm still learning about async js)

line 11 here: https://codepen.io/layige5800/pen/zYmEaQe

await new Promise(resolve => setTimeout(resolve, 20));  // only with this line I can make the input be emptied before the alert appears

Solution

  • window.alert pauses the main thread. This means what while the alert is open, no other code will run. So while you have told the browser to clear the input, that doesn't appear (repaint) instantly (see below), and during that time the alert opens, which causes the browser to stop doing everything else. By adding the setTimeout (you don't need the Promise) you are basically giving the browser time to complete the DOM update/paint (clearing the email) before creating the alert.

    Now, you might ask how this is possible in JS, generally a single-threaded program. Here is a blog post that explains your situation exactly (see the "Make a DOM Update Look Asynchronous w/ alert()" section).