0

I have a function bcrypt_hash() which is running very slow. After the user has entered a password, the program flow should continue while the BCrypt algorithm is running.

I have following code:

<script>
async function bcrypt_hash_async(s,rounds) {
  return new Promise(resolve => {
    resolve(bcrypt_hash(s,rounds));
  });
}

function test() {
    console.log("start calculation");
    bcrypt_hash_async("hello world", 15).then(hash => console.log(hash));
    console.log("continue program flow");
}
</script>

<input type="button" onclick="test()" value="Click me">

The JavaScript console shows the entries in the correct order:

start calculation
continue program flow
$2a$15$S1rOxr0THykuIOxqdehUh.gKDYIXpabfzRNyZ8y5FX.pu9..qEn4e

But actually, between "start calculation" and "continue program flow", the UI freezes until the calculation is done. How can I prevent that?

I am confused that the program hangs, although I have called the async function bcrypt_hash_async() without await.

Daniel Marschall
  • 3,739
  • 2
  • 28
  • 67
  • in a browser you really can't. you could try putting the work in a service worker. – Daniel A. White Oct 26 '20 at 22:03
  • 2
    Remember that there is no "continue running code while other code is running": Page JS is a single thread, and if you're running code, other code cannot run. So you can either do your work in a [ServiceWorker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) or [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) (which can run off-thread), or you have to structure your code in a way that has natural pauses in between your operations, so that the JS scheduler can keep things responsive. – Mike 'Pomax' Kamermans Oct 26 '20 at 22:04
  • 1
    perhaps a webworker rather than a serviceworker – Jaromanda X Oct 26 '20 at 22:04
  • What i did in image resampling was just releasing the thread every now and then, while calculating. As in, calculate for a few milliseconds, do UI stuff, repeat. Ghetto method, but worked. – ASDFGerte Oct 26 '20 at 22:10

0 Answers0