Javascript进度条不是“在飞行中”更新,而是一次性处理完成? [英] Javascript progress bar not updating 'on the fly', but all-at-once once process finished?

查看:79
本文介绍了Javascript进度条不是“在飞行中”更新,而是一次性处理完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,应该更新一个进度条作为循环
增量,但它只是着色进度条在一个循环实际完成后。我记得有一个类似的问题,如果我使用alert语句,着色将工作,所以我认为它与线程的并发。为了解决我的老问题,我使用setTimeout。

I have a loop which should be updating a progress bar as the loop increments, however it's only colouring the progress bar in one go after the loop has actually finished. I remember having a similar problem, if I used alert statements, the colouring would work, so I think it has to do with the concurrency of threads. To solve my old problem, I used setTimeout. However, this still isn't getting my progress bar coloured in real-time.

这里是我在做什么:

for (var i = 0; i < numOfRows; i++) {
    setTimeout('ColourBlock(' + i + ')', 0);

    // do_work
}

function ColourBlock (position){
    document.getElementById("block" + position).style.backgroundColor = "orange";
}

有人告诉我这可能是由于JavaScript优化?任何人都可以帮助吗?

Somebody told me it could be due to JavaScript optimization? Can anyone help please?

推荐答案

它是关于这样的事实,当代码使DOM或样式更改的快速序列,浏览器不尝试更新每个之间的视图。

It's not about threads. It's about the fact that when code makes a rapid sequence of DOM or style changes, the browser does not attempt to update the view between each one. Instead, it waits for things to calm down and then repaints.

如果你用一个非零的超时值(例如100毫秒)来描述一个序列,那么它就会等待事情平静下来,然后重新绘制。对于每个变化,那么你会看到它发生。正如你所写的那样,在零毫秒超时的情况下,所有的更新都会在很短的时间内发生 - 可能在一毫秒以下,除非你有成千上万的这些块。

If you coded up a sequence as you describe with a non-zero timeout value (say, 100 milliseconds) for each change, then you would see it happen. As you've written it, with a zero millisecond timeout, all the updates are going to happen within a very short period of time - probably well under a millisecond, unless you've got thousands of those blocks.

(请注意,你的示例代码不会给出100作为每个更改的超时值;你必须将它们递增到更远的位置,为每个更改添加100个,使用间隔定时器,并在上次更新后取消。)

(Note that your sample code wouldn't give 100 as the timeout to each change; you'd have to put them incrementally farther into the future, adding another 100 for each one. Or you could use an interval timer and cancel it after the last update.)

这篇关于Javascript进度条不是“在飞行中”更新,而是一次性处理完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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