Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

Making CPU Bound javascript feel responsive---webworkers?

I am writing a CPU intensive javascript application. I am running into a problem where sometimes the UI is locked while CPU-intensive calculation occurs. I know that the standard approach to solving this is to call setTimeout and let the event loop respond to UI events. However, that doesn't work for me and here's why.

When the page loads, the javascript vm needs to do a bunch of parsing and analyzing of chunks of data. This is truly background stuff, and I am calling setTimeout to run each chunk. However, this means that the user gets a very choppy UI experience until all chunks have been completed (can be up to 10 seconds for large files) and on every save. This is not acceptable.

I can think of 2 solutions, neither of which I really like:

  1. be more granular about the chunks, thus providing more opportunities for the event loop to run. But, I don't like this because the cpu code is already quite complex, but it typically runs well. Calling setTimeout throughout the cpu bound code would make it far more complicated
  2. Do more work on the server. However, I am running a node server and this would simply push the problem from the client to the server, with the added problem of increased bandwidth.

Fixing this would be trivial on a traditional thread-based VM. What should I do for Javascript?


UPDATE:

Some points that I forgot to mention:

Webworkers might be the solution, but they do still seem flaky. Does anyone have experience with them? Are they stable? Which modern browsers do not support them well? Are there any general problems with them?

Upvotes: 2

Views: 557

Answers (1)

zatatatata
zatatatata

Reputation: 4821

Depending on whether this application will ever become public or not, you have to decide whether you can use Web Workers, split the data up more or do server-side processing. For real-world applications the real solution would be doing heavy computation on the server since you can't expect the user to have the latest processor, it might be a mere netbook which will probably only cough a few times and then crash.

Web workers would be a solution when you can be sure that users have the latest browsers that support it, however if that's not the case, there's no way to shim it like most HTML5 stuff.

Based on what I know about your application, I'd say that you should send precomputed data to the client. Furthermore, Node.js is bad at doing hardcore computations so you might want to look into different data processing options on the server. Also, I don't think bandwidth will be a problem since you have to give the client the initial data anyway. How much bigger is the processed data?

Upvotes: 5

Related Questions