Decrease Javascript CPU Usage

I plan to write code to encrypt files in javascript locally. For large files and large key sizes, CPU usage is (naturally) quite large. In one script design, this often freezes the browser until the task is completed.

To improve responsiveness and allow users to do something else, I want to try to make the script β€œfriendlier” on the user's PC. The encryption process will read the file as a binary string, and then encrypt the string in pieces (something like 1KB / chunk - needs to be tested). I want to try to make HTML5-based users do their best as incremental as possible. Something like:

  • Spawn worker
  • Send an employee a block of binary data
  • Worker completes encryption, transfers a new fragment
  • The worker is dying.

It can also help with multi-core processors, immediately, having several workers at once.

Anyway, did anyone look at the intentional slowdown of the script to reduce CPU usage? Something like dividing the task of working encryption into separate operations and introducing a delay between them.

Timer interval callback every 100 ms (example).

Is the worker busy?
Yes - Wait another interval
No - Run next letter encryption

Advice / thoughts?

Does anyone have experience using workers? If you separate the main user interface from the intensification of work, making it work, does the reaction increase?

+4
javascript cpu-usage
Jul 27 '11 at 15:08
source share
1 answer

This uses nothing HTML5, but here is an example for calling a function every N milliseconds, assuming that you can determine the appropriate timeout. Basically, I am trying to help you by showing you a way to forcefully pause a certain amount of time before doing more processing.

function doSomething(){ clearTimeout(timeout); // do your "expensive" processing // ... // decide the job is done and return here or else // call doSomething again in sleepMS milliseconds timeout = setTimeout(doSomething,sleepMS); } var timeout; var sleepMS = 1000; doSomething(); 

EDIT

last line changed from

 var timeout = setTimeout(doSomething,1000); 

just for that

 doSomething() 

EDIT 2

Changed 1000 for sleepMS in a call to setTimeout, duh :)

+2
Jul 27 2018-11-17T00:
source share



All Articles