简体   繁体   中英

Multiple updates during one function call in JavaScript

I'm trying to write some script performing quite heavy computations. Thus, I'd like to inform user about progress by updating content on the site (for example, fraction of completed computations). Is it possible to achieve with JavaScript? Does JavaScript allow update of the content while invoked function is still running? Or maybe no matter what are the circumstances I can update the content only after invoked function is done?

Take a look at workers: http://www.html5rocks.com/en/tutorials/workers/basics/

It's made for heavy computation (at javascript scale ofc), and comes with some functions for updating the user about the state of the computation, it's multithreading in javascript basically.

Use timers

From your computing function, update global variables.

Then from main thread, use setTimeout() or setInterval() to query the global value periodically and update screen.

While your function is running, no screen updates will happen: UI thread has to fight for its time just like any other JS thread. You can do it by scheduling callbacks:

function f() {
  a();
  // update now
  b();
}

can be rewritten as

function f() {
  a();
  setTimeout(function() {
    b();
  }, 0);
}

The way this works, after a() , setTimeout will schedule the rest of the function, then exit. This is where UI thread can (and will) now grab control; then after it is done, the scheduled remainder will execute.

If you have things to do that fit the (quite severe) WebWorker restrictions, you can use them instead; however, they cannot touch UI, so redraws would be pointless (unless you do as Antoine says, and schedule an update function based on WebWorker-calculated parameters).

My few cents:

  • The easiest method to address is the most common way of simply showing a busy animation.

  • Try breaking your heavyweight computational code into pieces & update the progress bar.

  • Or as Antoine suggested, try using Web Workers .

Yes, probably you can do it. I don't know all details of your problem, but you should be aimed to socket.io and asynchronous node.js .

With node.js you can send process states to clients in real time and catch server responses with socket.io on client-side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM