【发布时间】:2017-03-12 10:38:23
【问题描述】:
我什至很难问这个问题,因为我不明白发生了什么。
基本上,我有一个旋转加载器元素,应该在我的 javascript 运行时显示。在 javascript 结束时,应关闭加载程序,并应显示一个模式,其中包含从数据库查询的数据。问题是加载程序永远不会显示。在创建模式之前查询运行大约需要 1 到 2 秒的等待时间。
function includeConnectionJS() {
if (!(typeof sforce === "object")) {
var connectionJS = document.createElement('script');
var documentHead = document.getElementsByTagName('head')[0];
connectionJS.src = '/soap/ajax/38.0/connection.js';
connectionJS.setAttribute('onload', 'createLoader();createModal();');
documentHead.appendChild(connectionJS);
} else {
createLoader();
// Checks to see if the loader element exists. If it does not, create the element and than toggle it to display it.
// If the element already exists, display the modal
createModal();
// Checks to see if the modal element exists, if it does not, create the element and than turn off the loader and display the modal.
// If the element already exists, turn off the loader and display the modal
}
}
我将 console.logs 放在我的方法中,我可以清楚地看到该方法正在被调用,if 语句全部通过,并且元素的可见性在正确的时间更改为正确的值。一切似乎都暗示它应该可以工作,但该元素从未真正显示出来。
我可以通过将 createModal 调用更改为如下所示来显示它:
setTimeout(function(){createModal()}, 100); // Most values for delay worked.
我不想为了显示加载器的效果而人为地延迟。
我主要关心的是 createModal 方法调用数据库。这些会导致 javascript 执行延迟(我同步调用它们,而不是异步调用它们)。我可以清楚地看到在查询之前加载程序显示被设置为“阻塞”,观察所有查询调用并返回,并看到加载程序的显示以正确的顺序变回“无”。不仅如此,如果我调用 createLoader();直接从控制台方法,它的工作原理。
我只是想不通我错过了什么。
【问题讨论】:
-
您描述的所有内容,从正确的顺序到
setTimeout“修复”问题听起来就像createModal()过早关闭加载程序。如果不查看您的其余代码,我们将无法为您提供帮助。黑暗中的一枪:如果你想告诉 JS 在 B 发生后执行 A(),你需要传递function() { A(); },而不是A();。 -
@ChrisG 不,Javascript 的本质是阻止对 UI 的更新,直到正在执行的代码完全完成。此外,javascript 在单线程中按顺序执行,因此
A将始终在B之后执行B(); A();。A在B完成之前永远无法启动
标签: javascript