I'm writing a small app that does some processing to an input that takes longer than a couple seconds, so I wanted to wrap the processing in a Modal, such as
function exec()
{
modal = document.getElementById("modal");
modal.style.display = "block";
// processing
modal.style.display = "none";
}
Here is the JFiddle: https://jsfiddle.net/6mufcet3/4/
From what I've read, Javascript is a synchronous language, but through some debugging it looks like it jumps straight to the for loop without showing the modal.
Also, if I set breakpoints in my browser's dev tools, it seems to work perfectly fine. I'm not a web developer and therefore don't really know how Javascript is executed; if things are being rearranged, etc.
You should use promises. The way you are implemented the exec function hide immediately the modal.
function execButton() {
modal = document.getElementById("inModal")
modal.style.display = "block"
// Get some time to show the modal
setTimeout(function() {
const longTask = new Promise(function(resolve, reject) {
let out = 0
for (let i = 0; i <= 1000; i++) {
out += i
console.log(i)
}
resolve(out)
})
longTask.then(function(out) {
modal.style.display = "none"
})
}, 100)
}
var button = document.getElementById("inButton")
button.onclick = execButton
.modal {
display: none;
position: fixed;
z-index: 10000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.3);
}
<button id="inButton" type="button" class="button">Open</button>
<div id="inModal" class="modal">
Modal
</div>
In the example I put the long task inside a setTimeout function, because the snippet needs some time to refresh the DOM.