js处理完成时的基本Javascript加载消息 [英] Basic Javascript loading message while js processing completes

查看:79
本文介绍了js处理完成时的基本Javascript加载消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我肯定这已经被问过1000次了,基本上我要做的就是更改页面元素的内容以显示加载消息,同时我的其他JavaScript代码(需要大量资源)完成。问题是直到其他JS处理完成后才显示消息,从而完全破坏了它的目的。一个简化的示例...

Im sure this has been asked 1000 times before, basically all I want to do is change the content of an element of the page to display a loading message while my other javascript code (quite resource intensive) completes. The problem is the message isnt displayed untill after the "other JS processing" has completed, thus defeating its purpose entirely. a simplified example...

<html>
<head>
    <title> crappity crapness </title>
    <script type="text/javascript">
        function showMessage(){
            document.getElementById("content").innerHTML = "please wait while we waste some time";
        }

        function wasteTime(){
            //alert("oh joy");
            pausecomp(3000);
            //alert("marvelous!");
        }

        function pausecomp(millis) 
        {
            var date = new Date();
            var curDate = null;

            do { curDate = new Date(); } 
            while(curDate-date < millis);
        } 

    </script>
</head>
<body>
    <div id="content">Blah</div>
    <br/>
    <a href="http://www.google.com" onclick="showMessage(); wasteTime();"> link </a>
</body>

如果我不评论哦 Joy警报,则div中的文本会立即更新。

if I uncomment the "oh Joy" alert, the text in the div gets updated Immediatly. how do I make it work without the alert?

我知道我一定会丢失一些简单的东西。
谢谢

I know I must be missing something simple. Thanks

推荐答案

听起来像您是在挑战Javascript是单线程的事实,但是浏览器不是。

It sounds like you're coming up against the fact that Javascript is single-threaded, but browsers are not.

基本上,您不能一次运行多个Javascript。但是,浏览器仍然必须执行Javascript之外的操作,并在可能的情况下继续执行。问题在于,未定义对DOM的修改是同步的(即,JS执行直到完成才停止)还是异步的(JS执行继续)。大多数浏览器都执行后者。但是JS执行仍然具有较高的优先级,并且许多DOM更新被推迟到JS执行必须停止并等待之前。警报框是一个很好的例子,因为它正在等待用户输入。

Basically, you can't have multiple pieces of Javascript running at once. However, the browser still has to do things outside of executing Javascript and proceeds to do so when it can. The problem is that whether modifying the DOM is synchronous (i.e. JS execution stops until it's done) or asynchronous (JS execution continues) isn't defined. Most browsers do the latter. But JS execution still has a quite high priority and a lot of DOM updates get deferred until the JS execution has to stop and wait. An alert box is an excellent example because it is waiting for user input.

做您想做的事情的方法是利用 setTimeout的优势(),它可以完成当前JS的工作,然后浏览器可以完成DOM的更新,然后可以执行JS,等待超时运行。

The way to do what you want to do is to advantage of setTimeout() which lets the current piece of JS finish, the browser can then finish updating the DOM, and then it can execute JS waiting to run on a timeout.

这篇关于js处理完成时的基本Javascript加载消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆