gpt4 book ai didi

javascript - 在不工作的模式中包装处理任务

转载 作者:行者123 更新时间:2023-11-30 13:56:51 26 4
gpt4 key购买 nike

我正在编写一个小应用程序,它对需要超过几秒钟的输入进行一些处理,所以我想将处理过程包装在模态中,例如

function exec()
{
modal = document.getElementById("modal");
modal.style.display = "block";

// processing

modal.style.display = "none";
}

这是 JFiddle: https://jsfiddle.net/6mufcet3/4/

据我所知,Javascript 是一种同步语言,但通过一些调试,它似乎直接跳转到 for 循环而不显示模态。

此外,如果我在浏览器的开发工具中设置断点,它似乎工作得很好。我不是 Web 开发人员,因此并不真正了解 Javascript 是如何执行的;如果事情正在重新安排等。

最佳答案

你应该使用 promise 。执行 exec 函数的方式会立即隐藏模态。

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>

在示例中,我将长任务放在 setTimeout 函数中,因为代码片段需要一些时间来刷新 DOM。

关于javascript - 在不工作的模式中包装处理任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com