html - Update webpage to show progress while javascript is running in in a loop -


i have written javascript takes 20-30 seconds process , want show progress updating progress bar on webpage.

i have used settimeout in attempt allow webpage re-drawn.

this how code looks like:

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 not work, know why not work, don't know how refactor code make work.

as know, problem here main process (the 1 takes lot of time), blocking rendering. that's because javascript (mostly) mono-threaded.

from point of view, have 2 solutions this. first 1 cut down main process different parts , rendering between each of them. i.e. have (using promises) :

var processparts = [/* array of func returning promises */];  function start(){     // call first process parts     var firstpartpromise = (processparts.shift())();     // chain other process parts interspersed updatedisplay     return processparts.reduce(function(prev, current){         return val.then(current).then(updatedisplay);     }, firstpartpromise); } 

you need polyfill promises (one here). if use jquery, have (bad non standard) implementation.

the second solution can use webworkers allows create threads in javascript. works on modern browsers. best solution in case. never used them supposed able stuff like:

var process = new worker("process.js");  worker.onmessage(function(event){     updateprogress(event.data.progress) }); 

and in process.js:

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

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -