在javascript中创建异步方法
我正在编写javascript代码来更新用户的界面。 此任务必须在后台完成,不应阻止任何内容。 代码当前正在阻止/崩溃浏览器,而while循环导致了该问题 我希望等待检查和安装完成,然后执行其他操作。我想避免编写这样的场景:TimeOut in a TimeOut in a TimeOut,这确实有效,但会让代码变得一团糟在javascript中创建异步方法,javascript,jquery,asynchronous,Javascript,Jquery,Asynchronous,我正在编写javascript代码来更新用户的界面。 此任务必须在后台完成,不应阻止任何内容。 代码当前正在阻止/崩溃浏览器,而while循环导致了该问题 我希望等待检查和安装完成,然后执行其他操作。我想避免编写这样的场景:TimeOut in a TimeOut in a TimeOut,这确实有效,但会让代码变得一团糟 updateChecking(); function updateChecking() { setTimeout(function() { if
updateChecking();
function updateChecking() {
setTimeout(function() {
if (settings.IsChecking === "True") {
var isChecking = false;
var isInstalling = false;
// PROBLEM, Wait till checking is completed
while (isChecking) {
var timerUpdateChecker = setInterval(function() {
getIsCheckingUpdates().done(function(resultIsChecking) {
if (resultIsChecking === "False") {
isChecking = true;
clearInterval(timerUpdateChecker);
}
});
}, 1000);
checkForSystemUpdates();
startCheckingDownloads();
// PROBLEM, Wait till installing is completed
while (isInstalling) {
setInstallerInterface();
var timerInstallChecker = setInterval(function() {
getIsInstallingUpdates().done(function(resultIsUpdating) {
if (resultIsUpdating === "False") {
isInstalling = true;
clearInterval(timerInstallChecker);
}
});
}, 1000);
}
viewUpdateInstalledAlert();
getAvailableUpdates();
unsetInstallerInterface();
};
}
}, 0);
}
有什么建议可以解决我的问题吗?
,而
循环一直运行到条件iffalse
。现在将变量设置为false并在调用时调用。所以我不确定while将如何工作。据我所知,它应该是而(!isChecking)
也就是说,您应该尝试替换setTimeout
和setInterval
并替换为事件。您可以创建自定义事件、分派和侦听。我认为这样会更有效率。大概是这样的:
var event = new Event('isInstalled');
在已安装的函数中,您可以分派事件:
window.dispatchEvent(event);
然后你监听事件来触发想要的函数
window.addEventListener('isInstalled', function(){
//whatever needs to happen when installed is done
})
使用setInterval
每秒重新运行检查程序可能不是一个好主意。