Attempting to complete exercise 4j in the above photo, the instructions are to display the message ‘Loading…’ in the console log, and then create a popup with the text ‘Purchased’.
The problem is that the ‘loading…’ doesn’t display in the console until after the ‘purchase’ alert is called and closed.
Attempted to rearrange the order of javascript code by putting the console.log line above the alert line.
Expected the console.log to display a string stating ‘loading…’ then after displaying the string, an alert box would appear.
Edit: Solution link: 1-exercise-solutions/lesson-04/4j.html
function loading() {
console.log('loading...');
alert('purchased');
}
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 50px;
}
.add {
background: yellow;
}
.buy {
background: orange;
}
```
<html>
<body>
<h3>
Spider-man comic
</h3>
<p>
Price: $8.99
</p>
<button class="add" onclick="
alert('added!');">add to cart</button>
<button class="buy" onclick="loading()">buy now</button>
<script>
// Your JavaScript goes here
console.log('Welcome!');
</script>
</body>
</html>
2
Answers
You can force
window.alert()
to execute afterconsole.log()
with asetTimeout()
of 0:However, note that in a practical app, you would:
alert()
to notify the user, as this blocks the rest of the page and is hard to control.async/await
orPromise
to notify the user after the action of purchasing has loaded in the background.For more info as to why this happens, see this response.
The reason you’re not seeing the ‘loading…’ message in the console until after the alert box is dismissed is due to how blocking operations are handled in JavaScript. When you call alert(), it halts the execution of the main thread until the user closes the alert. This happens even if there is a console.log() right before the alert() in your code.
The console.log() does execute before the alert(), but since the alert halts everything, you won’t get a chance to see the output in the console until the alert is handled. To allow the console to process and display the message before the alert pops up, you can use setTimeout. This schedules the alert() call on the JavaScript event queue, allowing the main thread to continue and process other operations, like updating the console, before the alert is displayed.
Here is how you can use setTimeout in your code: