多个javascript子例程的实时DOM显示 [英] Real-time DOM display of multiple javascript subroutines

查看:61
本文介绍了多个javascript子例程的实时DOM显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML表格,我必须填写一些javascript函数计算。 javascript函数有一些子程序,每个子程序进行一些计算并用结果填充HTML表。问题是,即使子程序花费一些时间进行计算,并且预期结果会在时间上连续出现,实际上结果会立即显示。我真的希望结果在计算时以几秒的速度显示。

I have an HTML table which I must fill with some javascript function calculations. The javascript function has some subroutines that each make some calculations and fill the HTML table with the results. The problem is that even if the subroutines spend some time to make the calculations and results are expected to appear successive in time, in fact the results are displayed at once. I really want the results to be displayed as they are calculated, at a few seconds pace.

推荐答案

Javascript是单线程的。



因此,尽管使用javascript进行DOM更改,但在当前JavaScript线程到达结束并退出之前,它不会更新显示。



你有两种可能的方法。



快速间隔



每一步每个任务/计算都在setInterval调用中进行。这意味着Javascript线程经常退出,允许dom更新。这将使您的计算时间更长。



使用网络工作者



WebWorker是一种相当新的浏览器功能,允许您将Javascript文件加载到后台线程中。然后,后台线程可以向主JS线程报告进度更新。然后主JS线程可以更新DOM。



http:/ /ejohn.org/blog/web-workers/ [ ^ ]



这取决于您需要的浏览器兼容性级别。如果需要传统的IE支持,我会选择快速间隔方法。如果没关系那么WebWorker。



---更新---



基于你的小提琴的问题是你正在使用睡眠方法。这会阻止Javascript线程阻止它更新UI。



我已经从End Logging中分离了Start Logging并实现了setTimeout来建立你想要的等待期三秒钟。



请看我的小提琴更新:



http://jsfiddle.net/da8qztym/1/ [ ^ ]
Javascript is single threaded.

So despite when you make DOM changes using javascript, it will not update the display until the current JavaScript thread reaches the end and exits.

You have two possible approaches.

Fast Interval

Each step of each task/calculation takes place in a setInterval call. This mean the Javascript thread frequently exits allowing the dom to updated. This will make your calculations take longer.

Use a Web Worker

A WebWorker is a fairly new browser feature that allows you to load a Javascript file into a background thread. The background thread can then report progress updates to the main JS thread. The main JS thread can then update the DOM.

http://ejohn.org/blog/web-workers/[^]

It depends on the level of browser compatibility you required. If legacy IE support is required I'd pick the fast interval approach. If it doesn't matter then the WebWorker.

--- Update ---

The issue based on your fiddle is that you're using a sleep method. This locks the Javascript thread stopping it from updating the UI.

I've seperated the Start Logging from the End Logging and implemented a setTimeout to establish your desired wait period of three seconds.

Please see my update to your fiddle:

http://jsfiddle.net/da8qztym/1/[^]


这篇关于多个javascript子例程的实时DOM显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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