更新页面以在javascript循环运行时显示进度 [英] Update webpage to show progress while javascript is running in in a loop

查看:53
本文介绍了更新页面以在javascript循环运行时显示进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的JavaScript需要20到30秒的处理时间,我想通过更新网页上的进度条来显示进度.

I have written javascript that takes 20-30 seconds to process and I want to show the progress by updating the progress bar on my webpage.

我使用setTimeout试图重新绘制网页.

I have used setTimeout in an attempt to allow webpage to be re-drawn.

这是我的代码的样子:

function lengthyFun(...){
   for(...){
      var progress = ...
      document.getElementById('progress-bar').setAttribute('style',"width:{0}%".format(Math.ceil(progress)));

      var x = ...

      // Processing
      setTimeout(function(x) { return function() { ...  }; }(x), 0);
   }
}

它不起作用,我知道为什么它不起作用,但是我不知道如何重构代码以使其起作用.

It does not work, I know why it does not work, but I don't know how to refactor my code to make it work.

推荐答案

您可能已经知道,这里的问题是您的主进程(该进程花费大量时间)阻止了任何渲染.这是因为JavaScript(大多数情况下)是单线程的.

As you probably know, the problem here is that you main process (the one that takes a lot of time), is blocking any rendering. That's because JavaScript is (mostly) mono-threaded.

从我的角度来看,您有两种解决方案可以做到这一点.第一个是将您的主要过程分解为不同的部分,并在每个部分之间进行渲染.IE.您可能会有类似的事情(使用Promises):

From my point of view, you have two solutions to do this. The first one is to cut down your main process into different parts and to do the rendering between each of them. I.e. you could have something like that (using Promises) :

var processParts = [/* array of func returning promises */];

function start(){
    // call the first process parts
    var firstPartPromise = (processParts.shift())();
    // chain it with all the other process parts interspersed by updateDisplay
    return processParts.reduce(function(prev, current){
        return val.then(current).then(updateDisplay);
    }, firstPartPromise);
}

您可能会需要兑现承诺(此处为一个).如果您使用jQuery,则它们有一个(糟糕的非标准)实现.

You will probably need a polyfill for the promises (one here). If you use jQuery, they have a (bad non standard) implementation.

第二种解决方案可以是使用网络工作者它允许您使用JavaScript创建线程.它适用于所有现代浏览器.在您的情况下,这可能是最好的解决方案.我从没使用过它们,但您应该可以执行以下操作:

The second solution can be to use webworkers which allows you to create threads in JavaScript. It works on all modern browsers. It is probably the best solution in your case. I never used them but you are supposed to be able to do stuff like:

var process = new Worker("process.js");

worker.onmessage(function(event){
    updateProgress(event.data.progress)
});

以及 process.js 中的

postMessage({progress: 0.1});
// stuff
postMessage({progress: 0.4});
// stuff
postMessage({progress: 0.7});
//etc

这篇关于更新页面以在javascript循环运行时显示进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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